from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from random import randint, shuffle
from django.utils import timezone
import requests, json, time, jwt, datetime, random, re, base64
from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from django.db.models import Q, F
from decimal import Decimal
from django.db.models import Count, Sum, Max, Min, Avg
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from django.shortcuts import render
from django.db.models.expressions import RawSQL
from django.db import transaction
from django_redis import get_redis_connection

from businesses.serializers import *
from equity_mall.utils.WXBizDataCrypt import WXBizDataCrypt
from equity_mall.utils.utils import bind_customer, random_str, mmpaymkttransfers, get_sign_HMACSHA1, redis_baidu_token, ryx_profitsharing_order
from activities.models import Channel
from customers.utils import pay_transactions_jsapi, AlipayOpen, favor_distributed_coupons, favor_query_coupons, pay_transactions_native, cmf_pay_transactions_jsapi, favor_query_coupons_sichun, favor_distributed_coupons_sichun
from managers.tasks import capture_payeeFullName
from equity_mall.utils.pages import MyPage, ElectLikePage
from businesses.filters import *
from businesses.utils import create_inviter_qrcode
from equity_mall.utils.qiniu_storage import pic_upload
from businesses.tasks import *
from equity_mall.utils.wash_level1 import get_user_by_code
from equity_mall.utils.common_msg import common_msg


class CustomerUserViceLoginView(APIView):

    permission_classes = ()

    def post(self, request):
        # unionid = 'opVLk6C9IuxspskDq8kmajCiy80Y'
        # user = CustomerUserVice.objects.get(unionid=unionid)
        # dic = {
        #     'exp': timezone.now() + datetime.timedelta(days=30),
        #     'iat': timezone.now(),
        #     'iss': 'business',
        #     'data': {
        #         'unionid': unionid,
        #         'id': user.id
        #     },
        # }
        # jwt_token = jwt.encode(dic, settings.CUSTOMER_SECRET_KEY, algorithm='HS256')
        # return Response({'user_id': user.id, 'token': jwt_token}, status=status.HTTP_200_OK)
        code = self.request.data.get('code', None)
        inviter_id = self.request.data.get('inviter_id', None)
        if not code:
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        appid = settings.CUSTOMER_APP_ID_WYH
        secret = settings.CUSTOMER_APP_SECRET_WYH
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'
        response = requests.get(url)
        data_dict = json.loads(response.content)
        if 'errcode' in data_dict:
            return Response({'error': str(data_dict['errcode']) + '错误,请联系管理员!'}, status=status.HTTP_400_BAD_REQUEST)
        openid = data_dict['openid']
        unionid = data_dict['unionid']
        user, create = CustomerUserVice.objects.update_or_create(unionid=unionid, defaults={'unionid': unionid, 'wyh_openid': openid})
        if create:
            user.create_time = datetime.datetime.now()
            user.save()
        if user.is_bind == 0:
            result = bind_customer(unionid)
            try:
                if result['result_code'] == 'success':
                    user.is_bind = 1
                    user.save()
            except:
                pass
        # if user.is_mobile == 0:
        #     try:
        #         customeruser = CustomerUser.objects.filter(wyh_openid=openid).first()
        #         if customeruser:
        #             CustomerUserViceRelation.objects.get_or_create(customeruser_id=customeruser.id, customeruservice_id=user.id, defaults={"customeruser_id": customeruser.id, "customeruservice_id": user.id})
        #             user.is_mobile = 1
        #             # user.customeruser_id = customeruser.id
        #             user.mobile = customeruser.mobile
        #             user.save()
        #     except:
        #         pass
        if inviter_id:
            inviter_user = CustomerUserVice.objects.filter(id=inviter_id)
            if inviter_user:
                if user.is_first == 1:
                    user.is_first = 0
                    user.inviter_id = inviter_id
                    user.save()
                    user_id = user.id
                    while True:
                        user = CustomerUserVice.objects.get(id=user_id)
                        origin_point = user.point
                        origin_obtain_point = user.obtain_point
                        new_point = origin_point + Decimal('100')
                        new_obtain_point = origin_obtain_point + Decimal('100')
                        result = CustomerUserVice.objects.filter(id=user_id, point=origin_point).update(
                            point=new_point,
                            obtain_point=new_obtain_point
                        )
                        if result == 0:
                            continue
                        break
                    recoad_data = {}
                    recoad_data['customeruservice_id'] = user.id
                    recoad_data['operate_type'] = 1
                    recoad_data['point_type'] = 1
                    recoad_data['point'] = + Decimal('100')
                    recoad_data['point_balance'] = new_point
                    recoad_data['explain'] = '新用户注册赠送积分'
                    get_point_record_db_model(user.id).objects.create(**recoad_data)
                    while True:
                        inviter_user = CustomerUserVice.objects.get(id=inviter_id)
                        origin_point = inviter_user.point
                        origin_obtain_point = inviter_user.obtain_point
                        new_point = origin_point + Decimal('100')
                        new_obtain_point = origin_obtain_point + Decimal('100')
                        result = CustomerUserVice.objects.filter(id=inviter_id, point=origin_point).update(
                            point=new_point,
                            obtain_point=new_obtain_point
                        )
                        if result == 0:
                            continue
                        break
                    recoad_data = {}
                    recoad_data['customeruservice_id'] = inviter_user.id
                    recoad_data['operate_type'] = 1
                    recoad_data['point_type'] = 3
                    recoad_data['point'] = + Decimal('100')
                    recoad_data['point_balance'] = new_point
                    recoad_data['explain'] = '邀请新用户注册'
                    get_point_record_db_model(inviter_user.id).objects.create(**recoad_data)
        if user.is_first == 1:
            user.is_first = 0
            user.save()
        if not user.username:
            user.username = '微邮惠会员'
            user.save()
        # unionid = 'opVLk6C9IuxspskDq8kmajCiy80Y'
        # user = CustomerUserVice.objects.get(unionid=unionid)
        dic = {
            'exp': timezone.now() + datetime.timedelta(days=30),
            'iat': timezone.now(),
            'iss': 'business',
            'data': {
                'unionid': unionid,
                'id': user.id
            },
        }
        jwt_token = jwt.encode(dic, settings.CUSTOMER_SECRET_KEY, algorithm='HS256')
        return Response({'user_id': user.id, 'token': jwt_token}, status=status.HTTP_200_OK)


class CustomerUserViceAuthLoginView(APIView):

    permission_classes = ()

    def get(self, request):
        user = self.request.iser
        code = self.request.query_params.get('code', None)
        logger.info(str(code))
        url = 'http://211.156.216.240:8086/ceshi_csb_broker'
        accessKey = '967c1a3435ff4797a9d66be7a80e9c4f'
        secretKey = 'cNMIL4twcDhAF2v8gbuvKqNJ3Ts='
        timestamp = int(time.time() * 1000)
        headers = {
            "_api_access_key": accessKey,
            "_api_name": 'getUserToOTSByCode',
            "_api_timestamp": str(timestamp),
            "_api_version": '1.0.0',
        }
        sign = get_sign_HMACSHA1(headers, secretKey)
        headers['_api_signature'] = sign
        headers['Content-Type'] = 'application/json'
        headers['User-Agent'] = 'PostmanRuntime/7.28.2'
        body = {
            "paramJson": {
                "code": code,
                "source": "GD-WYX",
                "serialNo": f"User{timestamp}"
            }
        }
        try:
            response = requests.post(url=url, headers=headers, data=json.dumps(body))
            result = response.json()
            logger.info(str(result))
            data = json.loads(result['body'])
            if not user.username:
                if 'nickName' in data:
                    user.username = data['nickName']
            if not user.avatar:
                if 'portraitUrlFull' in data:
                    user.avatar = data['portraitUrlFull']
            if user.is_mobile == 0:
                if 'mobile' in data and data['mobile']:
                    user.is_mobile = 1
                    user.mobile = data['mobile']
        except Exception as e:
            logger.info(str(e))
            pass
        user.save()
        if not user.username:
            user.username = '邮生活会员'
            user.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class CustomerUserViceYLXAuthLoginView(APIView):

    def get(self, request):
        user = self.request.iser
        ylx_code = self.request.query_params.get('ylx_code', None)
        org_id = self.request.query_params.get('org_id', None)
        logger.info(str(ylx_code))
        result = json.loads(get_user_by_code('QueryMemberInfoByCode', {"code": ylx_code}))
        logger.info(str(result))
        if result['meta']['code'] == 200:
            ylx_openid = result['data']['openId']
            ylx_mobile = result['data']['mobile']
            user.ylx_openid = ylx_openid
            user.mobile = ylx_mobile
            user.is_mobile = 1
            user.save()
            # AliDiscountCouponInfo.objects.filter(customeruservice_id__isnull=True, user_id=ylx_openid).update(customeruservice_id=user.id)
        if org_id:
            level = Level.objects.filter(account_nine=org_id).first()
            if level:
                return Response({'success': '操作成功', 'level_id': level.id}, status=status.HTTP_200_OK)
        return Response({'success': '操作成功', 'level_id': ''}, status=status.HTTP_200_OK)


class CustomerUserModelViewSet(ModelViewSet):

    def check_mobile(self, request):
        user = self.request.iser
        mobile = self.request.query_params.get('mobile', None)
        if mobile:
            check_customers = CustomerUserVice.objects.exclude(id=user.id).filter(mobile=mobile)
            if check_customers:
                return Response({'success': '', 'status': 1}, status=status.HTTP_200_OK)
        return Response({'success': '', 'status': 0}, status=status.HTTP_200_OK)

    def sms_codes(self, request):
        user = self.request.iser
        today = datetime.datetime.now() - datetime.timedelta(days=90)
        if user.update_time and user.update_time > today:
            return Response({'error': '90天内只能修改一次'}, status=status.HTTP_400_BAD_REQUEST)
        mobile = self.request.query_params.get('mobile', None)
        redis_conn = get_redis_connection("verify_code")
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({'error': '发送短信过于频繁!'}, status=status.HTTP_400_BAD_REQUEST)
        send_flag = redis_conn.get("send_flag_user_%s" % user.id)
        if send_flag:
            return Response({'error': '发送短信过于频繁!'}, status=status.HTTP_400_BAD_REQUEST)
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        content = f'【微邮付】登录验证码为：{sms_code}，若非本人操作，请忽略。'
        result = common_msg(mobile, content)
        return Response({"errmsg": "发送短信验证码成功"}, status=status.HTTP_200_OK)

    def info(self, request):
        user = self.request.iser
        data = CustomerUserViceInfoModelSerializer(user).data
        return Response(data, status=status.HTTP_200_OK)

    def equity_data(self, request):
        user = self.request.iser
        data = {}
        coupon_count = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id).count()
        point = 0
        data['coupon_count'] = coupon_count
        data['point'] = point
        data['dsh_order'] = 0
        data['dct_order'] = 0
        data['dhx_order'] = 0
        data['ywc_order'] = 0
        data['tk_order'] = 0
        order_set = OrderInfo.objects.filter(customeruservice_id=user.id).values('state').annotate(Count('id'))
        for order in order_set:
            if order['state'] == 6:
                data['dsh_order'] = order['id__count']
            elif order['state'] == 15:
                data['dct_order'] = order['id__count']
            elif order['state'] == 2:
                data['dhx_order'] = order['id__count']
            elif order['state'] == 14:
                data['ywc_order'] = order['id__count']
            elif order['state'] == 5:
                data['ywc_order'] += order['id__count']
            elif order['state'] == 8:
                data['ywc_order'] += order['id__count']
        return Response(data, status=status.HTTP_200_OK)

    def bind_mobile(self, request):
        user = self.request.iser
        if user.is_mobile:
            return Response({'error': '用户已经绑定手机号,请勿重复绑定!'}, status=status.HTTP_400_BAD_REQUEST)
        code = self.request.data.get('code', None)
        encryptedData = self.request.data.get('encryptedData', None)
        iv = self.request.data.get('iv', None)
        if not all([code, encryptedData, iv]):
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        appid = settings.CUSTOMER_APP_ID_WYH
        secret = settings.CUSTOMER_APP_SECRET_WYH
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'
        response = requests.get(url)
        data_dict = json.loads(response.content)
        if 'errcode' in data_dict:
            return Response({'error': str(data_dict['errcode']) + '错误,请联系管理员!'}, status=status.HTTP_400_BAD_REQUEST)
        session_key = data_dict['session_key']
        openid = data_dict['openid']
        pc = WXBizDataCrypt(appid, session_key)
        try:
            mobile = pc.decrypt(encryptedData, iv)['phoneNumber']
        except Exception as e:
            logging.error(e)
            print(e)
            return Response({'error': '获取手机号错误,请重新登录!'}, status=status.HTTP_400_BAD_REQUEST)
        customeruser, create = CustomerUser.objects.get_or_create(mobile=mobile, defaults={'mobile': mobile, 'create_time': datetime.datetime.now()})
        if create:
            AliDiscountCouponInfo.objects.filter(Q(mobile=mobile, customer_user__isnull=True)).update(customer_user_id=customeruser.id)
        if not customeruser.wyh_openid:
            customeruser.wyh_openid = openid
            customeruser.save()
        # check_customeruservice = CustomerUserVice.objects.filter(customeruser_id=customeruser.id)
        # if check_customeruservice:
        #     return Response({'error': '该手机号码重复绑定'}, status=status.HTTP_400_BAD_REQUEST)
        CustomerUserViceRelation.objects.get_or_create(customeruser_id=customeruser.id, customeruservice_id=user.id, defaults={"customeruser_id": customeruser.id, "customeruservice_id": user.id})
        user.is_mobile = 1
        # user.customeruser_id = customeruser.id
        user.mobile = customeruser.mobile
        user.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def synchronous_info(self, request):
        user = self.request.iser
        username = self.request.data.get('username', None)
        avatar = self.request.data.get('avatar', None)
        mobile = self.request.data.get('mobile', None)
        sms_code = self.request.data.get('sms_code', None)
        if username:
            user.username = username
        if avatar:
            user.avatar = avatar
        if mobile:
            today = datetime.datetime.now() - datetime.timedelta(days=90)
            if user.update_time and user.update_time < today:
                return Response({'error': '90天内只能修改一次'}, status=status.HTTP_400_BAD_REQUEST)
            if not sms_code:
                return Response({'error': '请上传短信校验码'}, status=status.HTTP_400_BAD_REQUEST)
            redis_conn = get_redis_connection("verify_code")
            sms_code_server = redis_conn.get("sms_%s" % mobile)
            if sms_code_server is None:
                return Response({'error': "短信验证码失效"}, status=status.HTTP_400_BAD_REQUEST)
            sms_code_server = sms_code_server.decode()
            if sms_code_server != str(sms_code):
                return Response({'error': "输入验证码有误"}, status=status.HTTP_400_BAD_REQUEST)
            redis_conn.delete("sms_%s" % mobile)
            user.mobile = mobile
            user.update_time = datetime.datetime.now()
            user.is_mobile = 1
        user.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def inviter_info(self, request):
        user = self.request.iser
        inviter_id = self.request.query_params.get('inviter_id', None)
        data = CustomerUserViceInfoModelSerializer(user).data
        data['inviter_point'] = Decimal(100)
        data['inviter_user_point'] = Decimal(100)
        inviter_user_set = CustomerUserVice.objects.filter(inviter_id=user.id)
        inviter_user_list = []
        for inviter_user in inviter_user_set:
            if inviter_user.avatar:
                inviter_user_list.append(
                    {
                        "avatar": inviter_user.avatar,
                        "username": inviter_user.username
                    }
                )
            else:
                inviter_user_list.append(
                    {
                        "avatar": 'https://jinjian.sutpay.cn/image/wyh_img14.png',
                        "username": '微信用户'
                    }
                )
        data['inviter_user_list'] = inviter_user_list
        if user.inviter_id:
            if inviter_id:
                if str(user.inviter_id) == str(inviter_id):
                    data['status'] = 1
                else:
                    data['status'] = 2
            else:
                data['status'] = 0
        else:
            data['status'] = 0
        if not user.inviter_qrcode:
            inviter_qrcode = create_inviter_qrcode(user.id)
            if inviter_qrcode:
                user.inviter_qrcode = inviter_qrcode
                user.save()
                data['inviter_qrcode'] = f'https://circle.sutpay.cn/{inviter_qrcode}'
            else:
                data['inviter_qrcode'] = ''
        else:
            data['inviter_qrcode'] = user.inviter_qrcode.url
        return Response(data, status=status.HTTP_200_OK)

    def assignment(self, request):
        user = self.request.iser
        data = []
        quest = {}
        quest['name'] = '每日签到'
        today = datetime.datetime.now()
        yesterday = today + datetime.timedelta(days=-1)
        today_date = today.strftime('%Y-%m-%d')
        yesterday_date = yesterday.strftime('%Y-%m-%d')
        today_sign = get_sign_in_db_model(user.id).objects.filter(customeruservice_id=user.id, date=today_date).first()
        if today_sign:
            quest['point'] = today_sign.point
            quest['status'] = 1
        else:
            quest['status'] = 0
            yesterday_sign = get_sign_in_db_model(user.id).objects.filter(customeruservice_id=user.id, date=yesterday_date).first()
            if not yesterday_sign:
                quest['point'] = Decimal(10)
            else:
                quest['point'] = Decimal(10) + yesterday_sign.award_point
        data.append(quest)
        return Response({'data': data}, status=status.HTTP_200_OK)

    def everyday_sign_in(self, request):
        user = self.request.iser
        today = datetime.datetime.now()
        yesterday = today + datetime.timedelta(days=-1)
        today_date = today.strftime('%Y-%m-%d')
        month = today.strftime('%Y-%m')
        yesterday_date = yesterday.strftime('%Y-%m-%d')
        today_sign = get_sign_in_db_model(user.id).objects.filter(customeruservice_id=user.id, date=today_date).first()
        if today_sign:
            return Response({'error': '今日已完成签到'}, status=status.HTTP_400_BAD_REQUEST)
        yesterday_sign = get_sign_in_db_model(user.id).objects.filter(customeruservice_id=user.id, date=yesterday_date).first()
        if not yesterday_sign:
            point = Decimal(10)
            award_point = 1
        else:
            point = Decimal(10) + yesterday_sign.award_point
            award_point = yesterday_sign.award_point + Decimal(1)
            if award_point > Decimal(5):
                award_point = Decimal(5)
        sign_in_data = {}
        sign_in_data['customeruservice_id'] = user.id
        sign_in_data['point'] = point
        sign_in_data['award_point'] = award_point
        sign_in_data['date'] = today_date
        sign_in_data['month'] = month
        instance, create = get_sign_in_db_model(user.id).objects.get_or_create(defaults=sign_in_data, customeruservice_id=user.id, date=today_date)
        if create:
            user_id = user.id
            while True:
                user = CustomerUserVice.objects.get(id=user_id)
                origin_point = user.point
                origin_obtain_point = user.obtain_point
                new_point = origin_point + point
                new_obtain_point = origin_obtain_point + point
                result = CustomerUserVice.objects.filter(id=user_id, point=origin_point).update(
                    point=new_point,
                    obtain_point=new_obtain_point
                )
                if result == 0:
                    continue
                break
            recoad_data = {}
            recoad_data['customeruservice_id'] = user.id
            recoad_data['operate_type'] = 1
            recoad_data['point_type'] = 5
            recoad_data['point'] = point
            recoad_data['point_balance'] = new_point
            recoad_data['explain'] = '每日签到'
            get_point_record_db_model(user.id).objects.create(**recoad_data)
            return Response({'success': '签到成功', 'point': point, 'total_point': new_point}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '重复签到'}, status=status.HTTP_400_BAD_REQUEST)

    def sign_in_history(self, request):
        user = self.request.iser
        month = self.request.query_params.get('month', None)
        if not month:
            month = datetime.datetime.now().strftime('%Y-%m')
        try:
            month_list = month.split('-')
            month_start = datetime.datetime(int(month_list[0]), int(month_list[1]), 1)
            if int(month_list[1]) != 12:
                month_end = datetime.datetime(int(month_list[0]), int(month_list[1]) + 1, 1)
            else:
                month_end = datetime.datetime(int(month_list[0]) + 1, int(month_list[1]) - 11, 1)
        except Exception as e:
            return Response({'error': '上传日期格式错误'}, status=status.HTTP_400_BAD_REQUEST)
        l1 = []
        if month_start.weekday() + 1 != 7:
            for i in range(month_start.weekday() + 1):
                l1.append({})
        queryset = get_sign_in_db_model(user.id).objects.filter(customeruservice_id=user.id, month=month)
        query_data = {}
        for query in queryset:
            query_data[query.date] = {"point": query.point, "award_point": query.award_point}
        yesterday = month_start + datetime.timedelta(days=-1)
        yesterday_date = yesterday.strftime('%Y-%m-%d')
        yesterday_sign = get_sign_in_db_model(user.id).objects.filter(customeruservice_id=user.id, date=yesterday_date).first()
        if yesterday_sign:
            query_data[yesterday_date] = {"point": yesterday_sign.point, "award_point": yesterday_sign.award_point}
        n = 1
        today = datetime.datetime.now()
        check_today = today.strftime('%Y-%m-%d')
        while True:
            if month_start >= month_end:
                return Response({'data': l1}, status=status.HTTP_200_OK)
            today_date = month_start.strftime('%Y-%m-%d')
            if today_date in query_data:
                if today_date == check_today:
                    l1.append({
                        'point': query_data[today_date]['point'],
                        'day': '今日',
                        'status': 1
                    })
                else:
                    l1.append({
                        'point': query_data[today_date]['point'],
                        'day': n,
                        'status': 1
                    })
            else:
                yesterday = month_start + datetime.timedelta(days=-1)
                yesterday_date = yesterday.strftime('%Y-%m-%d')
                if (month_start + datetime.timedelta(days=1)) >= today:
                    if yesterday_date in query_data:
                        award_point = query_data[yesterday_date]['award_point']
                        if today_date == check_today:
                            l1.append({
                                'point': award_point + Decimal(10),
                                'day': '今日',
                                'status': 0
                            })
                        else:
                            l1.append({
                                'point': award_point + Decimal(10),
                                'day': n,
                                'status': 0
                            })
                        award_point = award_point + Decimal(1)
                        if award_point > Decimal(5):
                            award_point = Decimal(5)
                        query_data[today_date] = {"point": award_point + Decimal(10), "award_point": award_point}
                    else:
                        l1.append({
                            'point': Decimal(10),
                            'day': n,
                            'status': 0
                        })
                        query_data[today_date] = {"point": Decimal(10), "award_point": Decimal(1)}
                else:
                    l1.append({
                        'point': '',
                        'day': n,
                        'status': 2
                    })
            month_start = month_start + datetime.timedelta(days=1)
            n += 1

    def agreement(self, request):
        is_agreement = self.request.data.get('is_agreement', None)
        if str(is_agreement) not in ['0', '1']:
            return Response({'error': '无效同意政策参数'}, status=status.HTTP_400_BAD_REQUEST)
        user = self.request.iser
        user.is_agreement = is_agreement
        user.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def inviter_details(self, request):
        user = self.request.iser
        inviter_begin_time = self.request.query_params.get('inviter_begin_time', None)
        inviter_end_time = self.request.query_params.get('inviter_end_time', None)
        search = self.request.query_params.get('search', None)
        data = {}
        query_set = CustomerUserViceInviterRecord.objects.filter(inviter_id=user.id)
        inviter_user_list = []
        total_count = CustomerUserViceInviterRecord.objects.filter(inviter_id=user.id).count()
        try:
            if inviter_begin_time:
                query_set = query_set.filter(create_time__gte=f'{inviter_begin_time} 00:00:00')
            if inviter_end_time:
                query_set = query_set.filter(create_time__lte=f'{inviter_end_time} 23:59:59')
        except:
            pass
        if search:
            query_set = query_set.filter(Q(qrcode__merchant__short_name__contains=search) | Q(qrcode__merchant__wyfMerchantID__contains=search))
        inviter_count = 0
        query_set = query_set.order_by('-create_time')
        for query in query_set:
            inviter_user = query.customeruservice
            qrcode = query.qrcode
            inviter_user_data = {}
            inviter_user_data['avatar'] = inviter_user.avatar if inviter_user.avatar else 'https://jinjian.sutpay.cn/image/wyh_img14.png'
            inviter_user_data['username'] = inviter_user.username if inviter_user.username else '邀请用户'
            inviter_user_data['inviter_time'] = query.inviter_time.strftime("%Y-%m-%d %H:%M:%S") if query.inviter_time else ''
            inviter_user_data['create_time'] = query.create_time.strftime("%Y-%m-%d %H:%M:%S")
            inviter_user_data['is_inviter'] = query.is_inviter
            inviter_user_data['merchant_name'] = qrcode.merchant.short_name if qrcode.merchant else '微邮付商户'
            if query.is_inviter == 1:
                inviter_count += 1
            inviter_user_list.append(inviter_user_data)
        data['inviter_user_list'] = inviter_user_list
        data['total_count'] = total_count
        data['inviter_count'] = inviter_count
        return Response(data, status=status.HTTP_200_OK)

    def upload_avatar(self, request):
        user = self.request.iser
        img = self.request.FILES.get('img', None)
        if not all([img]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        img_type = img.name.split('.')[-1]
        if img_type not in ['png', 'jpg']:
            return Response({'error': '请上传图片文件'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        try:
            mid_img = pic_upload(img_str)
            user.avatar = f'https://circle.sutpay.cn/{mid_img}'
            user.save()
        except Exception as e:
            logger.error(e)
            return Response({'error': '头像上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'success': '操作成功', 'img_id': f'{mid_img}'}, status=status.HTTP_200_OK)

    def upload_img(self, request):
        '''上传图片'''
        user = self.request.iser
        img = self.request.FILES.get('img', None)
        keyword = self.request.data.get('keyword', None)
        if not all([img, keyword]):
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        try:
            img_id = f'youhuiquanyi/customervice/{random_str()}.png'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            logger.error(e)
            return Response({'error': '图片上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['img_id'] = img_id
        if keyword == 'id_card_copy':
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
            id_card_copy = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"id_card_side": "front", "image": id_card_copy}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            try:
                response = requests.post(url, data=params, headers=headers)
                data_dict = response.json()
                data['id_card_name'] = data_dict['words_result']['姓名']['words']
                data['id_card_number'] = data_dict['words_result']['公民身份号码']['words']
                user.identification_front_copy = img_id
                user.save()
            except Exception as e:
                data['id_card_name'] = ''
                data['id_card_number'] = ''
                logger.error(e)
                pass
        elif keyword == 'id_card_national':
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
            id_card_national = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"id_card_side": "back", "image": id_card_national}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            try:
                response = requests.post(url, data=params, headers=headers)
                data_dict = response.json()
                card_period_end = data_dict['words_result']['失效日期']['words']
                card_period_begin = data_dict['words_result']['签发日期']['words']
                data['card_period_end'] = (card_period_end[0:4] + '-' + card_period_end[4:6] + '-' + card_period_end[6:8]) if card_period_end != '长期' else card_period_end
                data['card_period_begin'] = card_period_begin[0:4] + '-' + card_period_begin[4:6] + '-' + card_period_begin[6:8]
            except Exception as e:
                logger.error(e)
                pass
        elif keyword == 'bankcard':
            dic = {
                '邮储银行': '邮政储蓄银行',
                '工商银行': '工商银行',
                '民生银行': '民生银行',
                '交通银行': '交通银行',
                '中国银行': '中国银行',
                '招商银行': '招商银行',
                '中信银行': '中信银行',
                '浦东发展': '浦发银行',
                '兴业银行': '兴业银行',
                '光大信用卡中心': '光大银行',
                '广发': '广发银行',
                '平安银行': '平安银行',
                '北京银行': '北京银行',
                '华夏银行总行': '华夏银行',
                '农业银行': '农业银行',
                '建设银行': '建设银行',
                '宁波银行（贷）': '宁波银行',
            }
            lis = ['邮政储蓄银行', '工商银行', '民生银行', '交通银行',
                   '中国银行', '招商银行', '中信银行', '浦发银行',
                   '兴业银行', '光大银行', '广发银行', '平安银行', '北京银行',
                   '华夏银行', '农业银行', '建设银行', '宁波银行']
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard"
            img = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"image": img}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            response = requests.post(url, data=params, headers=headers)
            data_dict = response.json()
            try:
                data['bank_card_number'] = data_dict['result']['bank_card_number'].replace(' ', "")
                try:
                    data['bank_name'] = dic[data_dict['result']['bank_name']]
                except:
                    data['bank_name'] = '其他银行'
            except:
                return Response({"error": '您上传的银行卡无法识别，请手动添加！'}, status=status.HTTP_400_BAD_REQUEST)
        elif keyword == 'license_copy':
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
            img = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"image": img}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            try:
                response = requests.post(url, data=params, headers=headers)
                data_dict = response.json()
                data['capital'] = data_dict['words_result']['注册资本']['words']
                data['license_number'] = data_dict['words_result']['社会信用代码']['words']
                data['merchant_name'] = data_dict['words_result']['单位名称']['words']
                data['legal_person'] = data_dict['words_result']['法人']['words']
                data['cert_number'] = data_dict['words_result']['证件编号']['words']
                data['subject_type'] = data_dict['words_result']['组成形式']['words']
                data['date'] = data_dict['words_result']['成立日期']['words']
                data['company_address'] = data_dict['words_result']['地址']['words']
                data['qualification_type'] = data_dict['words_result']['经营范围']['words']
                data['type'] = data_dict['words_result']['类型']['words']
                data['effective'] = data_dict['words_result']['有效期']['words']
            except Exception as e:
                logger.error(e)
                pass
        return Response(data=data, status=status.HTTP_200_OK)

    def id_card_auth(self, request):
        user = self.request.iser
        id_card_name = self.request.data.get('id_card_name', None)
        id_card_number = self.request.data.get('id_card_number', None)
        identification_type = self.request.data.get('identification_type', '1')
        if not all([id_card_name]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        # if len(id_card_number) != 18:
        #     return Response({'error': '身份证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        # identify_result = chack_identify(id_card_number)
        # if 'error' in identify_result:
        #     return Response({'error': identify_result['error']}, status=status.HTTP_400_BAD_REQUEST)
        # if not identify_result['success']:
        #     return Response({'error': '身份证号码有误，请输入正确的号码'}, status=status.HTTP_400_BAD_REQUEST)
        user.realname = id_card_name
        user.idcode = id_card_number
        user.identification_type = identification_type
        user.is_auth = 2
        user.save()
        return Response({'success': '提交认证成功'}, status=status.HTTP_200_OK)

    def advertisement(self, request):
        data = []
        # data.append({
        #     'image': 'https://jinjian.sutpay.cn/image/wyh_bg160_12.png',
        #     'appid': '',
        #     'path': '/pages/tourism0519/tourism0519'
        # })
        data.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg160_16.png',
            'appid': 'wx5f0a0165d342d788',
            'path': '/interactiveActivity/luckyDraw/index?actId=630043403916275712'
        })
        data.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg160_17.png',
            'appid': 'wx5f0a0165d342d788',
            'path': '/subPackages/main/user/rechargingDetails?couponId=463017516731453440'
        })
        data.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg160_15.png',
            'appid': '',
            'path': '/pages/organ_pro_list/organ_pro_list?goods_tag=xiaomi'
        })
        return Response(data, status=status.HTTP_200_OK)

    def eight_advertisement(self, request):
        data = {}
        data['top_bg'] = 'https://jinjian.sutpay.cn/image/wyh_bg172.png'
        lists = []
        lists.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg172_1.png',
            'appid': '',
            'path': '/pages/group_buying/group_buying',
            'is_con': 0
        })
        lists.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg172_2.png',
            'appid': '',
            'path': '/pages/88dip_video_like/88dip_video_like',
            'is_con': 0
        })
        lists.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg172_3.png',
            'appid': 'wxbf07fc5376ab43a2',
            'path': 'pages/88act_publicity/88act_publicity',
            'is_con': 0
        })
        lists.append({
            'image': 'https://jinjian.sutpay.cn/image/wyh_bg172_4.png',
            'appid': 'wx5f0a0165d342d788',
            'path': 'subPackages/main/user/rechargingDetails?couponId=574672851241103360',
            'is_con': 0
        })
        data['arr'] = lists
        return Response(data, status=status.HTTP_200_OK)


class CustomerUserViceModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = CustomerUserViceFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = CustomerUserVice.objects.filter(inviter_id=user.id)
        return queryset

    def get_serializer_class(self):
        return InviterCustomerUserViceListModelSerializer

    def get_ylx_jump_parameter(self, request):
        data = self.request.query_params.get('data', None)
        logger.info(f'邮乐享跳转参数:{data}')
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class CustomerUserViceAddressModelViewSet(ModelViewSet):

    serializer_class = CustomerUserViceAddressModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = CustomerUserViceAddress.objects.filter(customeruservice_id=user.id, is_deleted=0).order_by('-create_time')
        return queryset

    def create(self, request, *args, **kwargs):
        user = self.request.iser
        place = self.request.data.get('place', None)
        province = self.request.data.get('province', None)
        city = self.request.data.get('city', None)
        district = self.request.data.get('district', None)
        mobile = self.request.data.get('mobile', None)
        receiver = self.request.data.get('receiver', None)
        is_default = self.request.data.get('is_default', None)
        sex = self.request.data.get('sex', 1)
        if not all([place, city, district, mobile, receiver, province]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
        address_data = {}
        address_data['place'] = place
        address_data['province'] = province
        address_data['city'] = city
        address_data['district'] = district
        address_data['mobile'] = mobile
        address_data['receiver'] = receiver
        address_data['customeruservice_id'] = user.id
        address_data['create_time'] = datetime.datetime.now()
        address_data['sex'] = sex
        address, create = CustomerUserViceAddress.objects.get_or_create(
            place=place,
            province=province,
            city=city,
            district=district,
            mobile=mobile,
            receiver=receiver,
            customeruservice_id=user.id,
            defaults=address_data
        )
        if not create and address.is_deleted == 1:
            address.is_deleted = 0
            address.save()
        if is_default:
            CustomerUserViceAddress.objects.filter(customeruservice_id=user.id).update(is_default=0)
            address.is_default = 1
            address.save()
        return Response({'success': '添加地址成功'}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        place = self.request.data.get('place', None)
        province = self.request.data.get('province', None)
        city = self.request.data.get('city', None)
        district = self.request.data.get('district', None)
        mobile = self.request.data.get('mobile', None)
        receiver = self.request.data.get('receiver', None)
        is_default = self.request.data.get('is_default', None)
        if place:
            instance.place = place
        if province:
            instance.province = province
        if city:
            instance.city = city
        if district:
            instance.district = district
        if receiver:
            instance.receiver = receiver
        if mobile:
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
            instance.mobile = mobile
        if str(is_default) in ['0', '1']:
            if str(is_default) == '1':
                CustomerUserViceAddress.objects.filter(customeruservice_id=user.id).update(is_default=0)
                instance.is_default = 1
        instance.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = 1
        instance.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class BindCardOrderModelViewSet(ModelViewSet):

    def get_queryset(self):
        user = self.request.iser
        queryset = BindCardOrder.objects.filter(customeruservice_id=user.id)
        return queryset

    def activity(self, request):
        user = self.request.iser
        if user.is_psbc_card != 0:
            return Response({'error': '您没有参与此次活动资格'}, status=status.HTTP_400_BAD_REQUEST)
        bindcardorder = BindCardOrder.objects.filter(customeruservice_id=user.id, customizeactivity__available_end_time__gte=datetime.datetime.now()).exclude(prize_status=5).first()
        if not bindcardorder or bindcardorder.create_time.strftime("%Y%m%d") != datetime.datetime.now().strftime("%Y%m%d"):
            if bindcardorder and bindcardorder.create_time.strftime("%Y%m%d") != datetime.datetime.now().strftime("%Y%m%d"):
                bindcardorder.prize_status = 5
                bindcardorder.order_status = 4
                bindcardorder.save()
            check_activity = CustomizeActivity.objects.filter(activity_type=5, activity_status=1, available_end_time__gte=datetime.datetime.now()).first()
            if not check_activity:
                return Response({'error': '您没有参与此次活动资格'}, status=status.HTTP_400_BAD_REQUEST)
            out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            out_refund_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            bindcardorder_data = {}
            bindcardorder_data['customeruservice_id'] = user.id
            bindcardorder_data['amount'] = 0.01
            bindcardorder_data['order_status'] = 1
            bindcardorder_data['description'] = '邮政一分钱验卡活动'
            bindcardorder_data['out_trade_no'] = out_trade_no
            bindcardorder_data['out_refund_no'] = out_refund_no
            bindcardorder_data['customizeactivity_id'] = check_activity.id
            bindcardorder, create = BindCardOrder.objects.get_or_create(defaults=bindcardorder_data, customeruservice_id=user.id, order_status=1)
        data = BindCardOrderRetrieveModelSerializer(bindcardorder).data
        return Response(data, status=status.HTTP_200_OK)

    def payment(self, request):
        user = self.request.iser
        order_id = self.request.query_params.get('order_id', None)
        business_qrcode = self.request.query_params.get('business_qrcode', None)
        if not order_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = BindCardOrder.objects.get(customeruservice_id=user.id, id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if bindcardorder.order_status != 1:
            return Response({'error': '订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if business_qrcode:
            bindcardorder.business_qrcode = business_qrcode
            bindcardorder.save()
        openid = user.wyh_openid
        amount = 1
        appid = settings.CUSTOMER_APP_ID_WYH
        data_json = {}
        data_json['appid'] = appid
        data_json['mchid'] = '1486198522'
        data_json['description'] = bindcardorder.description
        data_json['out_trade_no'] = bindcardorder.out_trade_no
        data_json['notify_url'] = 'https://api.sutpay.com/cpay/wxpay_result/'
        data_json['amount'] = {"total": amount}
        data_json['payer'] = {"openid": openid}
        data_dict = pay_transactions_jsapi(data_json, appid)
        # data_dict = pay_transactions_native(data_json)
        if 'code' in data_dict:
            return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
        data_dict['out_trade_no'] = bindcardorder.out_trade_no
        return Response(data_dict, status=status.HTTP_200_OK)

    def check_order(self, request):
        user = self.request.iser
        out_trade_no = self.request.query_params.get('out_trade_no', None)
        if not out_trade_no:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = BindCardOrder.objects.get(customeruservice_id=user.id, out_trade_no=out_trade_no)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            if 'PSBC' in bindcardorder.bank_type:
                return Response({'success': '查询成功', 'status': 1}, status=status.HTTP_200_OK)
            else:
                return Response({'success': '查询成功', 'status': 0}, status=status.HTTP_200_OK)
        except:
            return Response({'success': '查询成功', 'status': 0}, status=status.HTTP_200_OK)

    def turnplate(self, request):
        user = self.request.iser
        order_id = self.request.query_params.get('order_id', None)
        if not order_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = BindCardOrder.objects.get(customeruservice_id=user.id, id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if bindcardorder.prize_status != 6:
            return Response({'error': '状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivity = bindcardorder.customizeactivity
        check_customizeactivityrules_set = customizeactivity.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0)).exclude(count=0)
        if not check_customizeactivityrules_set:
            return Response({'error': '奖品库存不足,请稍后再试'}, status=status.HTTP_400_BAD_REQUEST)
        list_data = []
        scrollText1 = []
        scrollText2 = []
        scrollText3 = []
        for check_customizeactivityrules in check_customizeactivityrules_set:
            if check_customizeactivityrules.prize_type in [1, 2]:
                # scrollText1.append(check_customizeactivityrules.prize_type)
                scrollText2.append(check_customizeactivityrules.alidiscountcoupon.amount)
                scrollText3.append(1)
            else:
                # scrollText1.append(check_customizeactivityrules.prize_type)
                scrollText2.append(check_customizeactivityrules.cashactivity.cashactivityrule_set.all().first().amount)
                scrollText3.append(2)
            if check_customizeactivityrules.prize_type in [2, 3]:
                scrollText1.append(2)
            else:
                scrollText1.append(1)
            probability = int(check_customizeactivityrules.count)
            for i in range(probability):
                list_data.append(check_customizeactivityrules.id)
        scrollText1 = scrollText1*7
        scrollText2 = scrollText2*7
        scrollText3 = scrollText3*7
        scrollText1[0] = 0
        scrollText2[0] = 0
        scrollText3[0] = 0
        customizeactivityrules_id = random.choices(list_data, k=1)[0]
        customizeactivityrules = bindcardorder.customizeactivityflipcards
        if customizeactivityrules.win_type in [1, 2]:
            # scrollText1.append(customizeactivityrules.prize_type)
            scrollText2.append(customizeactivityrules.alidiscountcoupon.amount)
            scrollText3.append(1)
        else:
            # scrollText1.append(customizeactivityrules.prize_type)
            scrollText2.append(customizeactivityrules.cashactivity.cashactivityrule_set.all().first().amount)
            scrollText3.append(2)
        if customizeactivityrules.win_type in [2, 3]:
            scrollText1.append(2)
        else:
            scrollText1.append(1)
        instance = bindcardorder.customizeactivityflipcards
        customizeactivityflipcards = CustomizeActivityFlipCARDSModelSerializer(instance).data
        return Response({'scrollText1': scrollText1, 'scrollText2': scrollText2, 'scrollText3': scrollText3, 'customizeactivityflipcards': customizeactivityflipcards}, status=status.HTTP_200_OK)

    def prize_draw(self, request):
        user = self.request.iser
        order_id = self.request.query_params.get('order_id', None)
        if not order_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = BindCardOrder.objects.get(customeruservice_id=user.id, id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if bindcardorder.prize_status != 6:
            return Response({'error': '状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        bindcardorder.prize_status = 2
        bindcardorder.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def accept(self, request):
        user = self.request.iser
        order_id = self.request.data.get('order_id', None)
        if not order_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = BindCardOrder.objects.get(customeruservice_id=user.id, id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if bindcardorder.prize_status != 2:
            return Response({'error': '状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        instance = bindcardorder.customizeactivityflipcards
        if instance.open_status == 6:
            if instance.win_type in [1, 2]:
                alidiscountcouponinfo = instance.alidiscountcouponinfo
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                alidiscountcouponinfo.out_biz_no = out_biz_no
                alidiscountcouponinfo.save()
            elif instance.win_type == [3, 6]:
                cashactivitydata = instance.cashactivitydata
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                cashactivitydata.partner_trade_no = partner_trade_no
                cashactivitydata.save()
            else:
                return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        date_now = datetime.datetime.now()
        if instance.win_type == 1:
            if not login_id:
                return Response({'error': '请上传领取账户'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            out_biz_no = alidiscountcouponinfo.out_biz_no
            alipay_obj = AlipayOpen()
            template_id = alidiscountcoupon.template_id
            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.save()
                try:
                    instance.return_msg = result['sub_msg']
                    instance.save()
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
            if voucherinfo:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                user.is_psbc_card = 1
                user.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            if alidiscountcoupon.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = result['template_id']
                alidiscountcouponinfo.gmt_active = result['gmt_active']
                alidiscountcouponinfo.gmt_expired = result['gmt_expired']
                alidiscountcouponinfo.total_amount = result['total_amount']
                alidiscountcouponinfo.gmt_create = result['gmt_create']
                alidiscountcouponinfo.available_amount = result['available_amount']
                alidiscountcouponinfo.name = result['name']
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.mobile = user.mobile
                alidiscountcouponinfo.save()
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = alidiscountcoupon.template_id
                alidiscountcouponinfo.gmt_active = gmt_active
                alidiscountcouponinfo.gmt_expired = gmt_expired
                alidiscountcouponinfo.total_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.gmt_create = gmt_create
                alidiscountcouponinfo.available_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.name = alidiscountcoupon.activity_name
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.mobile = user.mobile
                alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            user.is_psbc_card = 1
            user.save()
            bindcardorder.prize_status = 3
            bindcardorder.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 2:
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            if alidiscountcoupon.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": alidiscountcoupon.template_id,
                "out_request_no": alidiscountcouponinfo.out_biz_no,
                "appid": appid,
                "stock_creator_mchid": alidiscountcoupon.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['message']
                instance.save()
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                user.is_psbc_card = 1
                user.save()
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            alidiscountcouponinfo.voucher_id = coupon_id
            alidiscountcouponinfo.user_id = openid
            alidiscountcouponinfo.template_id = result['stock_id']
            alidiscountcouponinfo.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.total_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.gmt_create = datetime.datetime.now()
            alidiscountcouponinfo.available_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.name = result['coupon_name']
            alidiscountcouponinfo.status = 1
            alidiscountcouponinfo.appid = appid
            alidiscountcouponinfo.mobile = user.mobile
            alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            user.is_psbc_card = 1
            user.save()
            bindcardorder.prize_status = 3
            bindcardorder.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 3:
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            cashactivity = instance.cashactivity
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            today_time_begin = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            today_time_end = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
            if encouragedraw:
                return Response({'error': '微信额度已达到今日上限,请明日领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, customeruservice_id=user.id, state=2)
            today_amount = Decimal('0')
            for encouragedraw in encouragedraw_set:
                today_amount += encouragedraw.amount
            today_amount += cashactivitydata.amount
            if today_amount > Decimal('500'):
                return Response({'error': '微信额度已达到今日上限,请明日领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                cashactivitydata.state = 5
                cashactivitydata.channel_id = cashactivity.wx_channel_id
                cashactivitydata.save()
                mchid = '1486198522'
                params = {
                    'mch_appid': appid,
                    'mchid': '1486198522',  # 商户号
                    'nonce_str': cashactivitydata.nonce_str,
                    'partner_trade_no': cashactivitydata.partner_trade_no,
                    'openid': openid,
                    'check_name': 'NO_CHECK',
                    'amount': int(cashactivitydata.amount * 100),
                    'desc': cashactivitydata.desc
                }
                data_dict = mmpaymkttransfers(params)
            if data_dict['result_code'] == 'SUCCESS':
                cashactivitydata.state = 2
                cashactivitydata.received_time = data_dict['payment_time']
                cashactivitydata.payment_no = data_dict['payment_no']
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = mchid
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                user.is_psbc_card = 1
                user.save()
                bindcardorder.prize_status = 3
                bindcardorder.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            else:
                cashactivitydata.return_msg = data_dict['err_code_des']
                cashactivitydata.state = 3
                cashactivitydata.received_time = date_now
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = mchid
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['err_code_des']
                instance.save()
                user.is_psbc_card = 1
                user.save()
                bindcardorder.prize_status = 4
                bindcardorder.save()
                return Response({'error': f'领取失败,{data_dict["err_code_des"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        elif instance.win_type == 6:
            if not login_id:
                return Response({'error': '请上传支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            if not realname:
                return Response({'error': '请上传支付宝账号实名账号'}, status=status.HTTP_400_BAD_REQUEST)
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            cashactivity = instance.cashactivity
            cashactivitydata.state = 5
            cashactivitydata.channel_id = cashactivity.ali_channel_id
            cashactivitydata.save()
            alipay_obj = AlipayOpen()
            trans_amount = str(cashactivitydata.amount)
            order_title = cashactivitydata.desc
            out_biz_no = cashactivitydata.partner_trade_no
            identity = login_id
            if cashactivity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(identity, realname, out_biz_no, trans_amount, order_title))
            elif cashactivity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_login_id(identity, realname, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                cashactivitydata.return_msg = result['sub_msg']
                cashactivitydata.state = 3
                cashactivitydata.received_time = date_now
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = 'alipay'
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = result["sub_msg"]
                instance.save()
                return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                cashactivitydata.received_time = result['trans_date']
                cashactivitydata.payment_no = result['pay_fund_order_id']
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = 'alipay'
                cashactivitydata.state = 2
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                try:
                    eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
                    capture_payeeFullName.apply_async(({"activityqrcode_id": cashactivitydata.id},), eta=eta)
                except:
                    pass
                user.is_psbc_card = 1
                user.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)

    def payment_psbc(self, request):
        user = self.request.iser
        if user.is_psbc_card == 1:
            return Response({'error': '重复验卡'}, status=status.HTTP_400_BAD_REQUEST)
        bindcardorder = BindCardOrder.objects.filter(customeruservice_id=user.id, order_status=1).first()
        if not bindcardorder:
            out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            out_refund_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            bindcardorder_data = {}
            bindcardorder_data['customeruservice_id'] = user.id
            bindcardorder_data['amount'] = 0.01
            bindcardorder_data['order_status'] = 1
            bindcardorder_data['description'] = '邮政一分钱验卡活动'
            bindcardorder_data['out_trade_no'] = out_trade_no
            bindcardorder_data['out_refund_no'] = out_refund_no
            bindcardorder, create = BindCardOrder.objects.get_or_create(defaults=bindcardorder_data, customeruservice_id=user.id, order_status=1)
        openid = user.wyh_openid
        amount = 1
        appid = settings.CUSTOMER_APP_ID_WYH
        data_json = {}
        data_json['appid'] = appid
        data_json['mchid'] = '1486198522'
        data_json['description'] = bindcardorder.description
        data_json['out_trade_no'] = bindcardorder.out_trade_no
        data_json['notify_url'] = 'https://api.sutpay.com/cpay/customervice_wxpay_result/'
        data_json['amount'] = {"total": amount}
        data_json['payer'] = {"openid": openid}
        data_dict = pay_transactions_jsapi(data_json, appid)
        # data_dict = pay_transactions_native(data_json)
        if 'code' in data_dict:
            if data_dict['code'] not in ['OUT_TRADE_NO_USED', 'ORDER_NOT_EXIST', 'ORDER_CLOSED', 'INVALID_REQUEST']:
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            else:
                out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                bindcardorder.out_trade_no = out_trade_no
                bindcardorder.save()
                data_json['out_trade_no'] = bindcardorder.out_trade_no
                data_dict = pay_transactions_jsapi(data_json, appid)
                if 'code' in data_dict:
                    return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
        data_dict['out_trade_no'] = bindcardorder.out_trade_no
        return Response(data_dict, status=status.HTTP_200_OK)


class JoinCustomizeActivityModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_serializer_class(self):
        if self.action == 'list':
            return CustomizeActivityModelSerializer
        else:
            return CustomizeActivityRetrieveModelSerializer

    def get_serializer_context(self):
        user = self.request.iser
        return {'user': user}

    def get_queryset(self):
        user = self.request.iser
        queryset = CustomizeActivity.objects.filter(activity_type=6, activity_status=1)
        return queryset

    def popup_pay_activity(self, request):
        user = self.request.iser
        customizeactivity = CustomizeActivity.objects.filter(activity_type=6, activity_status=1, available_end_time__gte=datetime.datetime.now()).last()
        if not customizeactivity:
            return Response({'activity': {}, 'status': 0}, status=status.HTTP_200_OK)
        join_data = {}
        join_data['customeruservice_id'] = user.id
        join_data['customizeactivity_id'] = customizeactivity.id
        join_activity, create = JoinCustomizeActivity.objects.get_or_create(defaults=join_data, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id)
        data = JoinCustomizeActivityRetrieveModelSerializer(join_activity).data
        if join_activity.is_popup == 1:
            return Response({'activity': data, 'status': 0}, status=status.HTTP_200_OK)
        join_activity.is_popup = 1
        join_activity.save()
        return Response({'activity': data, 'status': 1}, status=status.HTTP_200_OK)

    def join_pay_activity(self, request):
        user = self.request.iser
        activity_id = self.request.data.get('join_activity_id', None)
        if not activity_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            joincustomizeactivity = JoinCustomizeActivity.objects.get(id=activity_id, customeruservice_id=user.id)
        except:
            return Response({'error': '无效活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        if joincustomizeactivity.is_join != 0:
            return Response({'error': '不能重复参加'}, status=status.HTTP_400_BAD_REQUEST)
        joincustomizeactivity.is_join = 1
        joincustomizeactivity.join_time = datetime.datetime.now()
        joincustomizeactivity.save()
        return Response({'success': '参加成功'}, status=status.HTTP_200_OK)

    def pay_activity_schedule(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('join_activity_id', None)
        if not activity_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            joincustomizeactivity = JoinCustomizeActivity.objects.get(id=activity_id, customeruservice_id=user.id)
        except:
            return Response({'error': '无效活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        if joincustomizeactivity.is_join == 0:
            return Response({'error': '请先报名参加活动'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivity = joincustomizeactivity.customizeactivity
        customizeactivitypayrules = customizeactivity.customizeactivitypayrules
        join_time = joincustomizeactivity.join_time
        available_end_time = customizeactivity.available_end_time
        total_count = customizeactivitypayrules.total_count
        amount = customizeactivitypayrules.amount
        draw_counts = customizeactivitypayrules.draw_counts.split(',')
        limit_merchant_count_by_day = customizeactivitypayrules.limit_merchant_count_by_day
        if customizeactivitypayrules.is_limit_merchant == 0:
            queryset = get_point_record_db_model(user.id).objects.filter(
                pay_time__gte=join_time,
                pay_time__lte=available_end_time,
                amount__gte=amount,
                customeruservice_id=user.id,
                level__prov_id=7330
            ).values('shop_id').annotate(order_id=Min('id'))[0:total_count]
            if joincustomizeactivity.is_join == 1:
                if len(queryset) == total_count:
                    joincustomizeactivity.is_join = 2
                joincustomizeactivity.count = len(queryset)
                joincustomizeactivity.save()
            order_id_list = []
            for order in queryset:
                order_id_list.append(order['order_id'])
        else:
            merchant_id_list = CustomizeActivityPayRulesLimitMerchant.objects.filter(customizeactivity_id=customizeactivity.id).values_list('merchant_id', flat=True)
            queryset = get_point_record_db_model(user.id).objects.filter(
                pay_time__gte=join_time,
                pay_time__lte=available_end_time,
                amount__gte=amount,
                customeruservice_id=user.id,
                merchant_id__in=merchant_id_list
            )
            order_id_list = []
            check_date_order = {}
            check_order_num = 0
            for order in queryset:
                if check_order_num >= total_count:
                    break
                pay_time = f'{order.pay_time.strftime("%Y%m%d")}{order.merchant_id}'
                if pay_time not in check_date_order:
                    check_date_order[pay_time] = 0
                if check_date_order[pay_time] >= limit_merchant_count_by_day:
                    continue
                order_id_list.append(order.id)
                check_date_order[pay_time] = check_date_order[pay_time] + 1
                check_order_num += 1
            if joincustomizeactivity.is_join == 1:
                if len(order_id_list) == total_count:
                    joincustomizeactivity.is_join = 2
                joincustomizeactivity.count = len(order_id_list)
                joincustomizeactivity.save()
        queryset = get_point_record_db_model(user.id).objects.filter(id__in=order_id_list)
        schedule_list = []
        draw_list = []
        for i in range(total_count):
            try:
                query = queryset[i]
                order_data = {}
                order_data['pay_time'] = query.pay_time.strftime("%Y-%m-%d %H:%M:%S")
                order_data['amount'] = query.amount
                merchant = query.merchant
                if merchant:
                    order_data['merchant_name'] = merchant.name
                    order_data['store_header_copy'] = merchant.store_header_copy.url
                else:
                    order_data['merchant_name'] = '微邮付商户'
                    order_data['store_header_copy'] = 'https://manage.gdwxyf.com/internal/images/gdwxyf.png'
                if str(i + 1) in draw_counts:
                    order_data['is_draw'] = 1
                    if not query.customizeactivityflipcards:
                        customizeactivityrules = CustomizeActivityRules.objects.get(customizeactivity_id=customizeactivity.id, index=i + 1)
                        identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % user.id}'
                        instance_data = dict()
                        instance_data['identify'] = identify
                        instance_data['customeruservice_id'] = user.id
                        instance_data['gears'] = 1
                        instance_data['customizeactivity_id'] = customizeactivity.id
                        if customizeactivityrules.prize_type in [1, 2]:
                            instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                            instance_data['win_type'] = customizeactivityrules.prize_type
                        elif customizeactivityrules.prize_type in [3, 6]:
                            instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                            instance_data['win_type'] = customizeactivityrules.prize_type
                        instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                        if instance.win_type in [1, 2]:
                            instance.open_status = 2
                            instance.open_time = datetime.datetime.now()
                            instance.save()
                            alidiscountcoupon = instance.alidiscountcoupon
                            if alidiscountcoupon.remain_number <= 0:
                                x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                                if x:
                                    shuffle(x)
                                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                                    instance.alidiscountcoupon_id = alidiscountcoupon.id
                                    instance.save()
                                else:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                    return Response({'error': '奖品库存不足,请稍后再试'}, status=status.HTTP_400_BAD_REQUEST)
                            activity_id = alidiscountcoupon.id
                            while True:
                                alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                                activity_origin_send_count = alidiscountcoupon.send_count
                                activity_origin_remain_number = alidiscountcoupon.remain_number
                                activity_new_send_count = activity_origin_send_count + 1
                                activity_new_remain_number = activity_origin_remain_number - 1
                                if activity_new_remain_number < 0:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                    return Response({'error': '奖品库存不足,请稍后再试'}, status=status.HTTP_400_BAD_REQUEST)
                                result = AliDiscountCoupon.objects.filter(id=activity_id,
                                                                          send_count=activity_origin_send_count).update(
                                    send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                                if result == 0:
                                    continue
                                break
                            alidiscountcouponinfo_data = {}
                            alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                            alidiscountcouponinfo_data['level_id'] = instance.level_id
                            alidiscountcouponinfo_data['status'] = 0
                            alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                            out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % user.id}'
                            alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                            alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                            alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                            alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                            instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                            instance.save()
                        else:
                            instance.open_status = 2
                            instance.open_time = datetime.datetime.now()
                            instance.save()
                            cashactivity = instance.cashactivity
                            cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                            if cashactivityrule.amount > cashactivity.remain_amount:
                                instance.open_status = 3
                                instance.win_type = 4
                                instance.open_time = datetime.datetime.now()
                                instance.save()
                                return Response({'error': '奖品库存不足,请稍后再试'}, status=status.HTTP_400_BAD_REQUEST)
                            amount = cashactivityrule.amount
                            activity_id = cashactivity.id
                            while True:
                                activity = CashActivity.objects.get(id=activity_id)
                                activity_origin_take_amount = activity.take_amount
                                activity_origin_remain_amount = activity.remain_amount
                                if activity_origin_remain_amount < amount:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                    return Response({'error': '奖品库存不足,请稍后再试'}, status=status.HTTP_400_BAD_REQUEST)
                                activity_new_take_amount = activity_origin_take_amount + amount
                                activity_new_remain_amount = activity_origin_remain_amount - amount
                                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                                     remain_amount=activity_origin_remain_amount,
                                                                     id=activity_id).update(
                                    take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                                if result == 0:
                                    continue
                                break
                            date_now = datetime.datetime.now()
                            activity_data = {}
                            activity_data['amount'] = amount
                            activity_data['create_time'] = date_now
                            activity_data['cash_activity_id'] = activity.id
                            activity_data['level_id'] = instance.level_id
                            activity_data['state'] = 1
                            identify = random_str()
                            nonce_str = random_str()
                            activity_data['identify'] = identify
                            activity_data['nonce_str'] = nonce_str
                            activity_data['desc'] = activity.name
                            activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%07d" % user.id}'
                            activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                            activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                            instance.cashactivitydata_id = activity_dat.id
                            instance.amount = amount
                            instance.save()
                        query.customizeactivityflipcards_id = instance.id
                        query.save()
                    else:
                        instance = query.customizeactivityflipcards
                    if instance.open_status == 2:
                        draws = CustomizeActivityFlipCARDSModelSerializer(instance).data
                        draw_list.append(draws)
                        order_data['draws'] = draws
                    else:
                        order_data['draws'] = CustomizeActivityFlipCARDSModelSerializer(instance).data
                else:
                    order_data['is_draw'] = 0
                    order_data['draws'] = {}
                schedule_list.append(order_data)
            except:
                if str(i + 1) in draw_counts:
                    schedule_list.append({'is_draw': 1})
                else:
                    schedule_list.append({'is_draw': 0})
        return Response({"schedule_list": schedule_list, "draw_list": draw_list}, status=status.HTTP_200_OK)

    def receive_reward(self, request):
        user = self.request.iser
        reward_id = self.request.data.get('reward_id', None)
        if not reward_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = CustomizeActivityFlipCARDS.objects.get(id=reward_id, customeruservice_id=user.id)
        except:
            return Response({'error': '无效活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.open_status not in [2, 6]:
            return Response({'error': '奖励状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.open_status == 6:
            if instance.win_type in [1, 2]:
                alidiscountcouponinfo = instance.alidiscountcouponinfo
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                alidiscountcouponinfo.out_biz_no = out_biz_no
                alidiscountcouponinfo.save()
            elif instance.win_type in [3, 6]:
                cashactivitydata = instance.cashactivitydata
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                cashactivitydata.partner_trade_no = partner_trade_no
                cashactivitydata.save()
            else:
                return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        date_now = datetime.datetime.now()
        if instance.win_type == 1:
            if not login_id:
                return Response({'error': '请上传领取账户'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            out_biz_no = alidiscountcouponinfo.out_biz_no
            alipay_obj = AlipayOpen()
            template_id = alidiscountcoupon.template_id
            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.save()
                try:
                    instance.return_msg = result['sub_msg']
                    instance.save()
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
            if voucherinfo:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                user.is_psbc_card = 1
                user.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            if alidiscountcoupon.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = result['template_id']
                alidiscountcouponinfo.gmt_active = result['gmt_active']
                alidiscountcouponinfo.gmt_expired = result['gmt_expired']
                alidiscountcouponinfo.total_amount = result['total_amount']
                alidiscountcouponinfo.gmt_create = result['gmt_create']
                alidiscountcouponinfo.available_amount = result['available_amount']
                alidiscountcouponinfo.name = result['name']
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.mobile = user.mobile
                alidiscountcouponinfo.save()
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = alidiscountcoupon.template_id
                alidiscountcouponinfo.gmt_active = gmt_active
                alidiscountcouponinfo.gmt_expired = gmt_expired
                alidiscountcouponinfo.total_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.gmt_create = gmt_create
                alidiscountcouponinfo.available_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.name = alidiscountcoupon.activity_name
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.mobile = user.mobile
                alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 2:
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            if alidiscountcoupon.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": alidiscountcoupon.template_id,
                "out_request_no": alidiscountcouponinfo.out_biz_no,
                "appid": appid,
                "stock_creator_mchid": alidiscountcoupon.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['message']
                instance.save()
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                user.is_psbc_card = 1
                user.save()
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            alidiscountcouponinfo.voucher_id = coupon_id
            alidiscountcouponinfo.user_id = openid
            alidiscountcouponinfo.template_id = result['stock_id']
            alidiscountcouponinfo.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.total_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.gmt_create = datetime.datetime.now()
            alidiscountcouponinfo.available_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.name = result['coupon_name']
            alidiscountcouponinfo.appid = appid
            alidiscountcouponinfo.status = 1
            alidiscountcouponinfo.mobile = user.mobile
            alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 3:
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            cashactivity = instance.cashactivity
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            today_time_begin = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            today_time_end = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin,
                                                            received_time__lte=today_time_end,
                                                            return_msg__contains='已达到今日商户付款额度上限')
            if encouragedraw:
                return Response({'error': '微信额度已达到今日上限,请明日领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin,
                                                                received_time__lte=today_time_end,
                                                                customeruservice_id=user.id, state=2)
            today_amount = Decimal('0')
            for encouragedraw in encouragedraw_set:
                today_amount += encouragedraw.amount
            today_amount += cashactivitydata.amount
            if today_amount > Decimal('500'):
                return Response({'error': '微信额度已达到今日上限,请明日领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                cashactivitydata.state = 5
                cashactivitydata.channel_id = cashactivity.wx_channel_id
                cashactivitydata.save()
                mchid = '1486198522'
                params = {
                    'mch_appid': appid,
                    'mchid': '1486198522',  # 商户号
                    'nonce_str': cashactivitydata.nonce_str,
                    'partner_trade_no': cashactivitydata.partner_trade_no,
                    'openid': openid,
                    'check_name': 'NO_CHECK',
                    'amount': int(cashactivitydata.amount * 100),
                    'desc': cashactivitydata.desc
                }
                data_dict = mmpaymkttransfers(params)
            if data_dict['result_code'] == 'SUCCESS':
                cashactivitydata.state = 2
                cashactivitydata.received_time = data_dict['payment_time']
                cashactivitydata.payment_no = data_dict['payment_no']
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = mchid
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                    result = CashActivity.objects.filter(id=cash_activity_id,
                                                         distributed_amount=origin_distributed_amount).update(
                        distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                user.is_psbc_card = 1
                user.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            else:
                cashactivitydata.return_msg = data_dict['err_code_des']
                cashactivitydata.state = 3
                cashactivitydata.received_time = date_now
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = mchid
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['err_code_des']
                instance.save()
                user.is_psbc_card = 1
                user.save()
                return Response({'error': f'领取失败,{data_dict["err_code_des"]}', 'status': ''},
                                status=status.HTTP_400_BAD_REQUEST)
        elif instance.win_type == 6:
            if not login_id:
                return Response({'error': '请上传支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            if not realname:
                return Response({'error': '请上传支付宝账号实名账号'}, status=status.HTTP_400_BAD_REQUEST)
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            cashactivity = instance.cashactivity
            cashactivitydata.state = 5
            cashactivitydata.channel_id = cashactivity.ali_channel_id
            cashactivitydata.save()
            alipay_obj = AlipayOpen()
            trans_amount = str(cashactivitydata.amount)
            order_title = cashactivitydata.desc
            out_biz_no = cashactivitydata.partner_trade_no
            identity = login_id
            if cashactivity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(identity, realname, out_biz_no, trans_amount, order_title))
            elif cashactivity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_login_id(identity, realname, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                cashactivitydata.return_msg = result['sub_msg']
                cashactivitydata.state = 3
                cashactivitydata.received_time = date_now
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = 'alipay'
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = result["sub_msg"]
                instance.save()
                return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                cashactivitydata.received_time = result['trans_date']
                cashactivitydata.payment_no = result['pay_fund_order_id']
                cashactivitydata.customeruservice_id = user.id
                cashactivitydata.mchid = 'alipay'
                cashactivitydata.state = 2
                cashactivitydata.mobile = user.mobile
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                    result = CashActivity.objects.filter(id=cash_activity_id,
                                                         distributed_amount=origin_distributed_amount).update(
                        distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                try:
                    eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
                    capture_payeeFullName.apply_async(({"activityqrcode_id": cashactivitydata.id},), eta=eta)
                except:
                    pass
                user.is_psbc_card = 1
                user.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)

    def customizeactivity_limitmerchant_map(self, request):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        search = self.request.query_params.get('search', None)
        distance = self.request.query_params.get('distance', 500)
        activity_id = self.request.query_params.get('join_activity_id', None)
        distance = int(10000) / 1000
        user = self.request.iser
        if not all([longitude, latitude]):
            return Response({'error': '须上传当前位置经纬度'}, status=status.HTTP_400_BAD_REQUEST)
        if not activity_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            joincustomizeactivity = JoinCustomizeActivity.objects.get(id=activity_id, customeruservice_id=user.id)
        except:
            return Response({'error': '无效活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        queryset = Merchant.objects.filter(customizeactivitypayruleslimitmerchant__customizeactivity_id=joincustomizeactivity.customizeactivity_id, latitude__isnull=False).distinct()
        response_data = {}
        response_data['max_count'] = len(queryset)
        response_data['count'] = len(queryset)
        response_data['longitude'] = longitude
        response_data['latitude'] = latitude
        if search:
            queryset = queryset.filter(Q(short_name__contains=search) | Q(name__contains=search))
            response_data['count'] = len(queryset)
        gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
        sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
        queryset = queryset.annotate(distance=sql).filter(distance__lt=distance).order_by(F('distance').asc(nulls_last=True))
        serializer = MerchantListModelSerializer(queryset, many=True, context={'longitude': longitude, 'latitude': latitude})
        response_data['merchant_list'] = serializer.data
        return Response(response_data, status=status.HTTP_200_OK)


class AliDiscountCouponInfoModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = AliDiscountCouponInfoFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id).exclude(status__in=[13]).order_by('-id')
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return AliDiscountCouponInfoListModelSerializer
        else:
            return AliDiscountCouponInfoRetrieveModelSerializer

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        login_id = self.request.data.get('login_id', None)
        if instance.status != 0:
            return Response({'error': '当前券状态不可领取'}, status=status.HTTP_400_BAD_REQUEST)
        # if user.is_auth != 2:
        #     return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        activity = instance.alidiscountcoupon
        # if user.is_auth != 2 and activity.is_need_auth == 1:
        #     return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.coupon_channel == 1:
            if not login_id:
                return Response({'error': '请上传领取账户'}, status=status.HTTP_400_BAD_REQUEST)
            out_biz_no = instance.out_biz_no
            alipay_obj = AlipayOpen()
            template_id = activity.template_id
            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                try:
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                instance.voucher_id = voucher_id
                instance.login_id = login_id
                instance.template_id = result['template_id']
                instance.gmt_active = result['gmt_active']
                instance.gmt_expired = result['gmt_expired']
                instance.total_amount = result['total_amount']
                instance.gmt_create = result['gmt_create']
                instance.available_amount = result['available_amount']
                instance.name = result['name']
                instance.status = 1
                instance.mobile = user.mobile
                instance.save()
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                instance.voucher_id = voucher_id
                instance.login_id = login_id
                instance.template_id = activity.template_id
                instance.gmt_active = gmt_active
                instance.gmt_expired = gmt_expired
                instance.total_amount = activity.amount
                instance.gmt_create = gmt_create
                instance.available_amount = activity.amount
                instance.name = activity.activity_name
                instance.status = 1
                instance.mobile = user.mobile
                instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            try:
                customizeactivityflipcards = instance.customizeactivityflipcardS
                customizeactivityflipcards.received_time = datetime.datetime.now()
                customizeactivityflipcards.open_status = 4
                customizeactivityflipcards.save()
                bindcardorder = customizeactivityflipcards.bindcardorder
                bindcardorder.prize_status = 3
                bindcardorder.save()
            except:
                pass
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)
        elif activity.coupon_channel == 2:
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            if activity.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": activity.template_id,
                "out_request_no": instance.out_biz_no,
                "appid": appid,
                "stock_creator_mchid": activity.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            instance.voucher_id = coupon_id
            instance.user_id = openid
            instance.template_id = result['stock_id']
            instance.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            instance.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            instance.total_amount = result['normal_coupon_information']['coupon_amount']/100
            instance.gmt_create = datetime.datetime.now()
            instance.available_amount = result['normal_coupon_information']['coupon_amount']/100
            instance.name = result['coupon_name']
            instance.appid = appid
            instance.status = 1
            instance.mobile = user.mobile
            instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            try:
                customizeactivityflipcards = instance.customizeactivityflipcardS
                customizeactivityflipcards.received_time = datetime.datetime.now()
                customizeactivityflipcards.open_status = 4
                customizeactivityflipcards.save()
                bindcardorder = customizeactivityflipcards.bindcardorder
                bindcardorder.prize_status = 3
                bindcardorder.save()
            except:
                pass
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)
        else:
            voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
            user_id = user.ali_user_id
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            instance.voucher_id = voucher_id
            instance.user_id = user_id
            instance.gmt_active = gmt_active
            instance.gmt_expired = gmt_expired
            instance.total_amount = activity.amount
            instance.gmt_create = gmt_create
            instance.available_amount = activity.amount
            instance.name = activity.activity_name
            instance.status = 1
            instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            if not user.level_id:
                user.level_id = instance.level_id
                user.user_id = instance.companyuser_id
                user.save()
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.status in [1, 8, 9]:
            alidiscountcoupon = instance.alidiscountcoupon
            if alidiscountcoupon.coupon_channel == 1:
                alipayopen = AlipayOpen()
                result = json.loads(alipayopen.voucherquery(instance.voucher_id))
                if result['status'] == 'USED':
                    alidiscountcoupon.use_count += 1
                    alidiscountcoupon.save()
                    try:
                        if 'bill_details' in result:
                            for bill_datail in result['bill_details']:
                                instance.gmt_use = bill_datail['gmt_create']
                                bill_datail['voucherinfo_id'] = instance.id
                                AliDiscountCouponBillDetails.objects.create(**bill_datail)
                    except:
                        pass
                    try:
                        alidiscountcoupon_level = instance.alidiscountcoupon_level
                        alidiscountcoupon_level.use_number += 1
                        alidiscountcoupon_level.p_use_number += 1
                        alidiscountcoupon_level.save()
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_use_number += 1
                            parent.save()
                    except:
                        pass
                instance.status = instance.STATUS_ENUM[result['status']]
                instance.save()
            elif alidiscountcoupon.coupon_channel == 2:
                coupon_id = instance.voucher_id
                openid = instance.user_id
                appid = instance.appid
                if alidiscountcoupon.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                try:
                    if result['status'] == 'USED':
                        alidiscountcoupon.use_count += 1
                        alidiscountcoupon.save()
                        try:
                            if 'bill_details' in result:
                                for bill_datail in result['bill_details']:
                                    instance.gmt_use = bill_datail['gmt_create']
                                    bill_datail['voucherinfo_id'] = instance.id
                                    AliDiscountCouponBillDetails.objects.create(**bill_datail)
                        except:
                            pass
                        try:
                            alidiscountcoupon_level = instance.alidiscountcoupon_level
                            alidiscountcoupon_level.use_number += 1
                            alidiscountcoupon_level.p_use_number += 1
                            alidiscountcoupon_level.save()
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_use_number += 1
                                parent.save()
                        except:
                            pass
                        instance.status = 7
                        instance.gmt_use = datetime.datetime.now()
                    elif result['status'] == 'EXPIRED':
                        instance.status = 12
                    instance.save()
                except:
                    pass
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class CustomizeActivityModelViewSet(ModelViewSet):

    # pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = CustomizeActivityFilter

    def get_queryset(self):
        if self.action in ['limit_customizeactivity_detail', 'lucky_draw', 'benben_customizeactivity', 'benben_lucky_draw']:
            queryset = CustomizeActivity.objects.filter(activity_status=1, activity_type__in=[7, 8, 6, 9, 10], available_end_time__gte=datetime.datetime.now())
        else:
            queryset = CustomizeActivity.objects.filter(activity_status=1, activity_type__in=[7, 8, 6], available_end_time__gte=datetime.datetime.now())
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = serializer.data
        today = datetime.datetime.now()
        elect_activity = NewYearsShoppingFestivalElect.objects.filter(available_begin_time__lte=today, available_end_time__gte=today).exclude(activity_state=0).first()
        if elect_activity:
            elect_activity_data = {}
            elect_activity_data['id'] = elect_activity.id
            elect_activity_data['activity_name'] = '年货节评选'
            elect_activity_data['activity_description'] = '''1、活动时间:
2023/12/20 00:00:00-2024/02/02 23:59:59。
2、每个账号每天可投5次票，同一天内只可以对同一作品投一票。
3、同一微信号、同一手机号码、同一银行卡号、同一身份证号码、同一手机设备，符合其中一个条件者视为同-用户。'''
            elect_activity_data['activity_type'] = 100
            elect_activity_data['available_begin_time'] = elect_activity.available_begin_time.strftime('%Y-%m-%d')
            elect_activity_data['available_end_time'] = elect_activity.available_end_time.strftime('%Y-%m-%d')
            elect_activity_data['activity_status'] = {}
            data.insert(0, elect_activity_data)
        return Response(data)

    def get_serializer_class(self):
        return CustomizeActivityLimitModelSerializer

    def limit_customizeactivity(self, request):
        queryset = self.get_queryset().filter(activity_type=7)
        if not queryset:
            return Response([], status=status.HTTP_200_OK)
        user = self.request.iser
        data = CustomizeActivityLimitModelSerializer(queryset, many=True).data
        return Response(data, status=status.HTTP_200_OK)

    def retrieve(self, request, *args, **kwargs):
        customizeactivity = self.get_object()
        user = self.request.iser
        if customizeactivity.activity_type == 7:
            if customizeactivity.is_white == 1:
                is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
                if not is_white:
                    return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            if customizeactivity.activity_status == 2:
                return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            if customizeactivity.activity_status != 1:
                return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
            check_customizeactivityrules_set = customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type__in=[4, 5]))
            data = {}
            lists = CustomizeActivityRulesListModelSerializer(customizeactivityrules_set, many=True).data
            if not check_customizeactivityrules_set:
                lists[-1] = {
                    "id": "X",
                    "prize_type": 4,
                    "prize_type_str": '谢谢参与',
                    "activity_info": {
                        "id": "",
                        "activity_name": "",
                        "activity_id": "",
                        "rule": "",
                        "available_begin_time": '',
                        "available_end_time": '',
                        "amount": ''
                    }
                }
            data['lists'] = lists
            data['activity_description'] = customizeactivity.activity_description
            data['id'] = customizeactivity.id
            data['activity_name'] = customizeactivity.activity_name
            data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            date_now = datetime.datetime.now()
            week = date_now.weekday()
            customizeactivitylotteryrules = customizeactivity.customizeactivitylotteryrules
            start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
            end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
            publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
            publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
            if customizeactivitylotteryrules.activity_mode == 1:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    data['status'] = 1
                else:
                    data['status'] = 0
                data['time'] = f'每天{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
            else:
                if str(week+1) not in customizeactivitylotteryrules.week_days:
                    data['status'] = 0
                else:
                    if publish_start_time <= date_now and publish_end_time >= date_now:
                        data['status'] = 1
                    else:
                        data['status'] = 0
                week_days = customizeactivitylotteryrules.week_days
                week_days = week_days.replace('1', '周一').replace('2', '周二').replace('3', '周三').replace('4', '周四').replace('5', '周五').replace('6', '周六').replace('7', '周日')
                data['time'] = f'逢{week_days}{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
            data['point'] = customizeactivitylotteryrules.point
            if customizeactivitylotteryrules.free_limit == 1:
                join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
                check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
                data['free_count'] = join_limit_by_user_count - check_count
            else:
                join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
                check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id, open_time__gte=publish_start_time, open_time__lte=publish_end_time).count()
                data['free_count'] = join_limit_by_user_count - check_count
            data['remain_point'] = user.point
            return Response(data, status=status.HTTP_200_OK)
        else:
            if customizeactivity.is_white == 1:
                is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
                if not is_white:
                    return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            if customizeactivity.activity_status == 2:
                return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            if customizeactivity.activity_status != 1:
                return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
            location = []
            for customizeactivityrules in customizeactivityrules_set:
                location.append(customizeactivityrules.index)
            check_customizeactivityrules_set = customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type__in=[4, 5]))
            data = {}
            check_customizeactivityrules_data = {}
            for check_customizeactivityrules in check_customizeactivityrules_set:
                check_customizeactivityrules_data[check_customizeactivityrules.index] = {
                    "index": check_customizeactivityrules.index, "isGrid": 1, "icon": check_customizeactivityrules.icon
                }
            lists = []
            for i in range(56):
                if i in location:
                    if i in check_customizeactivityrules_data:
                        lists.append(check_customizeactivityrules_data[i])
                    else:
                        lists.append({"index": i,"isGrid": 1,"icon": "https://jinjian.sutpay.cn/image/wyh_micon8.png"})
                else:
                    lists.append({"index": i,"isGrid": 0,"icon": ""})
            user_index_data = {}
            user_index_data['customizeactivity_id'] = customizeactivity.id
            user_index_data['customeruservice_id'] = user.id
            user_index_data['index'] = location[0]
            user_index, create = CustomizeActivityUserIndex.objects.get_or_create(defaults=user_index_data, customizeactivity_id=customizeactivity.id, customeruservice_id=user.id)
            data['index'] = user_index.index
            data['lists'] = lists
            data['activity_description'] = customizeactivity.activity_description
            data['id'] = customizeactivity.id
            data['activity_name'] = customizeactivity.activity_name
            data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            date_now = datetime.datetime.now()
            week = date_now.weekday()
            customizeactivitylotteryrules = customizeactivity.customizeactivitylotteryrules
            start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
            end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
            publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
            publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
            if customizeactivitylotteryrules.activity_mode == 1:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    data['status'] = 1
                else:
                    data['status'] = 0
                data['time'] = f'每天{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
            else:
                if str(week+1) not in customizeactivitylotteryrules.week_days:
                    data['status'] = 0
                else:
                    if publish_start_time <= date_now and publish_end_time >= date_now:
                        data['status'] = 1
                    else:
                        data['status'] = 0
                week_days = customizeactivitylotteryrules.week_days
                week_days = week_days.replace('1', '周一').replace('2', '周二').replace('3', '周三').replace('4', '周四').replace('5', '周五').replace('6', '周六').replace('7', '周日')
                data['time'] = f'逢{week_days}{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
            data['point'] = customizeactivitylotteryrules.point
            if customizeactivitylotteryrules.free_limit == 1:
                join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
                check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
                data['free_count'] = join_limit_by_user_count - check_count
            else:
                join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
                check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id, open_time__gte=publish_start_time, open_time__lte=publish_end_time).count()
                data['free_count'] = join_limit_by_user_count - check_count
            data['remain_point'] = user.point
            return Response(data, status=status.HTTP_200_OK)

    def limit_customizeactivity_detail(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('activity_id', None)
        if not activity_id:
            return Response({'error': '缺少活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            customizeactivity = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_white == 1:
            is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
            if not is_white:
                return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status == 2:
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status != 1:
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
        check_customizeactivityrules_set = customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type__in=[4, 5]))
        data = {}
        lists = CustomizeActivityRulesListModelSerializer(customizeactivityrules_set, many=True).data
        if not check_customizeactivityrules_set:
            lists[-1] = {
                "id": "X",
                "prize_type": 4,
                "prize_type_str": '谢谢参与',
                "activity_info": {
                    "id": "",
                    "activity_name": "",
                    "activity_id": "",
                    "rule": "",
                    "available_begin_time": '',
                    "available_end_time": '',
                    "amount": ''
                }
            }
        data['lists'] = lists
        data['activity_description'] = customizeactivity.activity_description
        data['id'] = customizeactivity.id
        data['activity_name'] = customizeactivity.activity_name
        data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        date_now = datetime.datetime.now()
        week = date_now.weekday()
        customizeactivitylotteryrules = customizeactivity.customizeactivitylotteryrules
        start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
        end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
        publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
        publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
        if customizeactivitylotteryrules.activity_mode == 1:
            if publish_start_time <= date_now and publish_end_time >= date_now:
                data['status'] = 1
            else:
                data['status'] = 0
            data['time'] = f'每天{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
        else:
            if str(week+1) not in customizeactivitylotteryrules.week_days:
                data['status'] = 0
            else:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    data['status'] = 1
                else:
                    data['status'] = 0
            week_days = customizeactivitylotteryrules.week_days
            week_days = week_days.replace('1', '周一').replace('2', '周二').replace('3', '周三').replace('4', '周四').replace('5', '周五').replace('6', '周六').replace('7', '周日')
            data['time'] = f'逢{week_days}{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
        data['point'] = customizeactivitylotteryrules.point
        if customizeactivitylotteryrules.free_limit == 1:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
            data['free_count'] = join_limit_by_user_count - check_count
        elif customizeactivitylotteryrules.free_limit == 2:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id, open_time__gte=publish_start_time, open_time__lte=publish_end_time).count()
            data['free_count'] = join_limit_by_user_count - check_count
        else:
            customize_activity_lottery_rules_user_free_count = CustomizeActivityLotteryRulesUserFreeCount.objects.filter(customizeactivity_id=customizeactivity.id, customeruservice_id=user.id).first()
            if not customize_activity_lottery_rules_user_free_count:
                # inviter_count = CustomerUserVice.objects.filter(inviter_id=user.id, inviter_time__gte=customizeactivity.available_begin_time, inviter_time__lte=customizeactivity.available_end_time).count()
                inviter_count = CustomerUserViceInviterRecord.objects.filter(inviter_id=user.id, inviter_time__gte=customizeactivity.available_begin_time, inviter_time__lte=customizeactivity.available_end_time).count()
                if inviter_count >=3:
                    customize_activity_lottery_rules_user_free_count_data = {}
                    customize_activity_lottery_rules_user_free_count_data['customizeactivity_id'] = customizeactivity.id
                    customize_activity_lottery_rules_user_free_count_data['customeruservice_id'] = user.id
                    customize_activity_lottery_rules_user_free_count_data['count'] = 1
                    CustomizeActivityLotteryRulesUserFreeCount.objects.get_or_create(customizeactivity_id=customizeactivity.id,
                                                                              customeruservice_id=user.id, defaults=customize_activity_lottery_rules_user_free_count_data)
                    data['free_count'] = 1
                else:
                    data['free_count'] = 0
            else:
                check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
                free_count = customize_activity_lottery_rules_user_free_count.count - check_count
                data['free_count'] = free_count
        data['remain_point'] = user.point
        data['is_point'] = customizeactivitylotteryrules.is_point
        return Response(data, status=status.HTTP_200_OK)

    def lucky_draw(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('activity_id', None)
        if not activity_id:
            return Response({'error': '缺少必传参数', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            customizeactivity = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_white == 1:
            is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
            if not is_white:
                return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2 and customizeactivity.is_need_auth == 1:
            return Response({'error': '请先完成实名认证', 'state': '0'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status == 2:
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status != 1:
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)

        date_now = datetime.datetime.now()
        week = date_now.weekday()
        customizeactivitylotteryrules = customizeactivity.customizeactivitylotteryrules
        start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
        end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
        publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
        publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
        if customizeactivitylotteryrules.activity_mode == 1:
            if publish_start_time <= date_now and publish_end_time >= date_now:
                pass
            else:
                return Response({'error': '未到活动时间'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            if str(week+1) not in customizeactivitylotteryrules.week_days:
                return Response({'error': '未到活动时间'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    pass
                else:
                    return Response({'error': '未到活动时间'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivitylotteryrules.free_limit == 1:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
            free_count = join_limit_by_user_count - check_count
        elif customizeactivitylotteryrules.free_limit == 2:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id, open_time__gte=publish_start_time, open_time__lte=publish_end_time).count()
            free_count = join_limit_by_user_count - check_count
        else:
            customize_activity_lottery_rules_user_free_count = CustomizeActivityLotteryRulesUserFreeCount.objects.filter(customizeactivity_id=customizeactivity.id, customeruservice_id=user.id).first()
            if not customize_activity_lottery_rules_user_free_count:
                # inviter_count = CustomerUserVice.objects.filter(inviter_id=user.id, inviter_time__gte=customizeactivity.available_begin_time, inviter_time__lte=customizeactivity.available_end_time).count()
                inviter_count = CustomerUserViceInviterRecord.objects.filter(inviter_id=user.id, inviter_time__gte=customizeactivity.available_begin_time, inviter_time__lte=customizeactivity.available_end_time).count()
                if inviter_count >=3:
                    customize_activity_lottery_rules_user_free_count_data = {}
                    customize_activity_lottery_rules_user_free_count_data['customizeactivity_id'] = customizeactivity.id
                    customize_activity_lottery_rules_user_free_count_data['customeruservice_id'] = user.id
                    customize_activity_lottery_rules_user_free_count_data['count'] = 1
                    customize_activity_lottery_rules_user_free_count, create = CustomizeActivityLotteryRulesUserFreeCount.objects.get_or_create(customizeactivity_id=customizeactivity.id, customeruservice_id=user.id, defaults=customize_activity_lottery_rules_user_free_count_data)
                else:
                    return Response({'error': '您还未获得抽奖资格'}, status=status.HTTP_400_BAD_REQUEST)
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
            free_count = customize_activity_lottery_rules_user_free_count.count - check_count
        if customizeactivitylotteryrules.is_point == 0:
            if free_count <= 0:
                return Response({'error': '您还未获得抽奖资格'}, status=status.HTTP_400_BAD_REQUEST)
        if free_count > 0:
            is_free = 1
        else:
            if user.point < customizeactivitylotteryrules.point:
                return Response({'error': '积分不足'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                is_free = 0
                user_id = user.id
                while True:
                    user = CustomerUserVice.objects.get(id=user_id)
                    origin_point = user.point
                    origin_use_point = user.use_point
                    if origin_point < customizeactivitylotteryrules.point:
                        return Response({'error': '积分不足'}, status=status.HTTP_400_BAD_REQUEST)
                    new_point = origin_point - customizeactivitylotteryrules.point
                    new_use_point = origin_use_point + customizeactivitylotteryrules.point
                    result = CustomerUserVice.objects.filter(id=user_id, point=origin_point).update(
                        point=new_point,
                        use_point=new_use_point
                    )
                    if result == 0:
                        continue
                    break
                recoad_data = {}
                recoad_data['customeruservice_id'] = user.id
                recoad_data['operate_type'] = 2
                recoad_data['point_type'] = 4
                recoad_data['point'] = customizeactivitylotteryrules.point
                recoad_data['point_balance'] = new_point
                recoad_data['explain'] = '参与活动抽奖消耗'
                get_point_record_db_model(user.id).objects.create(**recoad_data)
        check_customizeactivityrules_set = customizeactivity.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type__in=[4, 5]))
        if not check_customizeactivityrules_set:
            data = {}
            data["id"] = 'X'
            identify = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            instance_data = dict()
            instance_data['identify'] = identify
            instance_data['customeruservice_id'] = user.id
            instance_data['gears'] = 1
            instance_data['customizeactivity_id'] = customizeactivity.id
            instance_data['open_status'] = 3
            instance_data['open_time'] = datetime.datetime.now()
            instance_data['is_free'] = is_free
            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
            data["take_id"] = instance.id
            data["amount"] = ''
            data["activity_name"] = ''
            data["msg"] = ''
            data["available_time"] = ''
            data["win_type_str"] = '谢谢参与'
            data["win_type"] = 4
            return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
        else:
            list_data = []
            for check_customizeactivityrules in check_customizeactivityrules_set:
                probability = int(check_customizeactivityrules.count)
                for i in range(probability):
                    list_data.append(check_customizeactivityrules.id)
            customizeactivityrules_id = random.choices(list_data, k=1)[0]
            customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
            identify = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            instance_data = dict()
            instance_data['identify'] = identify
            instance_data['customeruservice_id'] = user.id
            instance_data['gears'] = 1
            instance_data['customizeactivity_id'] = customizeactivity.id
            instance_data['is_free'] = is_free
            if customizeactivityrules.prize_type in [1, 2]:
                instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                instance_data['win_type'] = customizeactivityrules.prize_type
            elif customizeactivityrules.prize_type in [3, 6]:
                instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                instance_data['win_type'] = customizeactivityrules.prize_type
            elif customizeactivityrules.prize_type == 5:
                instance_data['point'] = customizeactivityrules.point
                instance_data['win_type'] = customizeactivityrules.prize_type
            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
            if instance.win_type == 4:
                instance.open_status = 3
                instance.open_time = datetime.datetime.now()
                instance.save()
                data = {}
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = ''
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = '谢谢参与'
                data["win_type"] = 4
                return Response({'success': '谢谢参与', 'data': data},status=status.HTTP_200_OK)
            elif instance.win_type in [1, 2]:
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                alidiscountcoupon = instance.alidiscountcoupon
                data = {}
                if alidiscountcoupon.remain_number <= 0:
                    x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                    if x:
                        shuffle(x)
                        alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                        instance.alidiscountcoupon_id = alidiscountcoupon.id
                        instance.save()
                    else:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                activity_id = alidiscountcoupon.id
                while True:
                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = alidiscountcoupon.send_count
                    activity_origin_remain_number = alidiscountcoupon.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    if activity_new_remain_number < 0:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                    if result == 0:
                        continue
                    break
                alidiscountcouponinfo_data = {}
                alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                alidiscountcouponinfo_data['level_id'] = instance.level_id
                alidiscountcouponinfo_data['status'] = 0
                alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                alidiscountcouponinfo_data['mobile'] = user.mobile
                alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                alidiscountcouponinfo_data['customeruservice_id'] = user.id
                alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = alidiscountcoupon.amount
                data["activity_name"] = alidiscountcoupon.activity_name
                data["msg"] = alidiscountcoupon.floor_amount
                data["available_time"] = f'{alidiscountcoupon.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{alidiscountcoupon.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
            elif instance.win_type == 5:
                data = {}
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = instance.point
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = f''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
            else:
                data = {}
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                cashactivity = instance.cashactivity
                cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                if cashactivityrule.amount > cashactivity.remain_amount:
                    instance.open_status = 3
                    instance.win_type = 4
                    instance.open_time = datetime.datetime.now()
                    instance.save()
                    data['id'] = customizeactivityrules_id
                    data['take_id'] = instance.id
                    data["amount"] = ''
                    data["activity_name"] = ''
                    data["msg"] = ''
                    data["available_time"] = ''
                    data["win_type_str"] = '谢谢参与'
                    data["win_type"] = 4
                    return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                amount = cashactivityrule.amount
                activity_id = cashactivity.id
                while True:
                    activity = CashActivity.objects.get(id=activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    if activity_origin_remain_amount < amount:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                    if result == 0:
                        continue
                    break
                date_now = datetime.datetime.now()
                activity_data = {}
                activity_data['amount'] = amount
                activity_data['create_time'] = date_now
                activity_data['cash_activity_id'] = activity.id
                activity_data['level_id'] = instance.level_id
                activity_data['state'] = 1
                identify = random_str()
                nonce_str = random_str()
                activity_data['identify'] = identify
                activity_data['nonce_str'] = nonce_str
                activity_data['desc'] = activity.name
                activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                activity_data['customeruservice_id'] = user.id
                activity_data['mobile'] = user.mobile
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                instance.cashactivitydata_id = activity_dat.id
                instance.amount = amount
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = amount
                data["activity_name"] = cashactivity.name
                data["msg"] = ''
                data["available_time"] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)

    def claim_draw(self, request):
        user = self.request.iser
        reward_id = self.request.data.get('reward_id', None)
        if not reward_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = CustomizeActivityFlipCARDS.objects.get(id=reward_id, customeruservice_id=user.id)
        except:
            return Response({'error': '无效活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.open_status not in [2, 6]:
            return Response({'error': '奖励状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.open_status == 6:
            if instance.win_type in [1, 2]:
                alidiscountcouponinfo = instance.alidiscountcouponinfo
                out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                alidiscountcouponinfo.out_biz_no = out_biz_no
                alidiscountcouponinfo.save()
            elif instance.win_type in [3, 6]:
                cashactivitydata = instance.cashactivitydata
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                cashactivitydata.partner_trade_no = partner_trade_no
                cashactivitydata.save()
            else:
                return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        instance.mobile = user.mobile
        if instance.win_type == 1:
            if not login_id:
                return Response({'error': '请上传领取账户'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            out_biz_no = alidiscountcouponinfo.out_biz_no
            alipay_obj = AlipayOpen()
            template_id = alidiscountcoupon.template_id
            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.save()
                try:
                    instance.return_msg = result['sub_msg']
                    instance.save()
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
            if voucherinfo:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                user.is_psbc_card = 1
                user.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            if alidiscountcoupon.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = result['template_id']
                alidiscountcouponinfo.gmt_active = result['gmt_active']
                alidiscountcouponinfo.gmt_expired = result['gmt_expired']
                alidiscountcouponinfo.total_amount = result['total_amount']
                alidiscountcouponinfo.gmt_create = result['gmt_create']
                alidiscountcouponinfo.available_amount = result['available_amount']
                alidiscountcouponinfo.name = result['name']
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.mobile = user.mobile
                alidiscountcouponinfo.save()
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = alidiscountcoupon.template_id
                alidiscountcouponinfo.gmt_active = gmt_active
                alidiscountcouponinfo.gmt_expired = gmt_expired
                alidiscountcouponinfo.total_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.gmt_create = gmt_create
                alidiscountcouponinfo.available_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.name = alidiscountcoupon.activity_name
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.mobile = user.mobile
                alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 2:
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            if alidiscountcoupon.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": alidiscountcoupon.template_id,
                "out_request_no": alidiscountcouponinfo.out_biz_no,
                "appid": appid,
                "stock_creator_mchid": alidiscountcoupon.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['message']
                instance.save()
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                user.is_psbc_card = 1
                user.save()
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            alidiscountcouponinfo.voucher_id = coupon_id
            alidiscountcouponinfo.user_id = openid
            alidiscountcouponinfo.template_id = result['stock_id']
            alidiscountcouponinfo.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.total_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.gmt_create = datetime.datetime.now()
            alidiscountcouponinfo.available_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.name = result['coupon_name']
            alidiscountcouponinfo.appid = appid
            alidiscountcouponinfo.status = 1
            alidiscountcouponinfo.mobile = user.mobile
            alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type in [3, 6]:
            date_now = datetime.datetime.now()
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            if instance.win_type == 3:
                appid = settings.CUSTOMER_APP_ID_WYH
                openid = user.wyh_openid
                today_time_begin = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                today_time_end = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
                if encouragedraw:
                    return Response({'error': '微信额度已达到今日上限,请使用支付宝APP扫码领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, customer_user_id=user.id, state=2)
                today_amount = Decimal('0')
                for encouragedraw in encouragedraw_set:
                    today_amount += encouragedraw.amount
                today_amount += cashactivitydata.amount
                if today_amount > Decimal('100'):
                    return Response({'error': '微信额度已达到今日上限,请使用支付宝APP扫码领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    cashactivitydata.state = 5
                    cashactivitydata.save()
                    mchid = '1486198522'
                    params = {
                        'mch_appid': appid,
                        'mchid': '1486198522',  # 商户号
                        'nonce_str': cashactivitydata.nonce_str,
                        'partner_trade_no': cashactivitydata.partner_trade_no,
                        'openid': openid,
                        'check_name': 'NO_CHECK',
                        'amount': int(cashactivitydata.amount * 100),
                        'desc': cashactivitydata.desc
                    }
                    data_dict = mmpaymkttransfers(params)
                if data_dict['result_code'] == 'SUCCESS':
                    cashactivitydata.state = 2
                    cashactivitydata.received_time = data_dict['payment_time']
                    cashactivitydata.payment_no = data_dict['payment_no']
                    cashactivitydata.mchid = mchid
                    cashactivitydata.mobile = user.mobile
                    cashactivitydata.save()
                    instance.received_time = datetime.datetime.now()
                    instance.open_status = 4
                    instance.save()
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        origin_distributed_amount = activity.distributed_amount
                        new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                        result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                        if result == 0:
                            continue
                        break
                    user.is_psbc_card = 1
                    user.save()
                    return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
                else:
                    cashactivitydata.return_msg = data_dict['err_code_des']
                    cashactivitydata.state = 3
                    cashactivitydata.received_time = date_now
                    cashactivitydata.mchid = mchid
                    cashactivitydata.mobile = user.mobile
                    cashactivitydata.save()
                    instance.received_time = datetime.datetime.now()
                    instance.open_status = 6
                    instance.return_msg = data_dict['err_code_des']
                    instance.save()
                    return Response({'error': f'领取失败,{data_dict["err_code_des"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if not login_id:
                    return Response({'error': '请上传领取支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
                if not realname:
                    return Response({'error': '请上传领取支付宝账号实名姓名'}, status=status.HTTP_400_BAD_REQUEST)
                cashactivitydata.state = 5
                cashactivitydata.save()
                alipay_obj = AlipayOpen()
                trans_amount = str(cashactivitydata.amount)
                order_title = cashactivitydata.desc
                out_biz_no = cashactivitydata.partner_trade_no
                identity = login_id
                if cashactivitydata.cash_activity.ali_channel_id == 8:
                    result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(identity, realname, out_biz_no, trans_amount, order_title))
                elif cashactivitydata.cash_activity.ali_channel_id == 11:
                    result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
                else:
                    result = json.loads(alipay_obj.transunitransfer_login_id(identity, realname, out_biz_no, trans_amount, order_title))
                if result['code'] != '10000':
                    cashactivitydata.return_msg = result['sub_msg']
                    cashactivitydata.state = 3
                    cashactivitydata.received_time = date_now
                    cashactivitydata.mchid = 'alipay'
                    cashactivitydata.mobile = user.mobile
                    cashactivitydata.save()
                    instance.received_time = datetime.datetime.now()
                    instance.open_status = 6
                    instance.return_msg = result["sub_msg"]
                    instance.save()
                    return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    cashactivitydata.received_time = result['trans_date']
                    cashactivitydata.payment_no = result['pay_fund_order_id']
                    cashactivitydata.mchid = 'alipay'
                    cashactivitydata.state = 2
                    cashactivitydata.mobile = user.mobile
                    cashactivitydata.save()
                    instance.received_time = datetime.datetime.now()
                    instance.open_status = 4
                    instance.save()
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        origin_distributed_amount = activity.distributed_amount
                        new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                        result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                        if result == 0:
                            continue
                        break
                    try:
                        eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
                        capture_payeeFullName.apply_async(({"activityqrcode_id": cashactivitydata.id},), eta=eta)
                    except:
                        pass
                    return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 5:
            user_id = user.id
            while True:
                user = CustomerUserVice.objects.get(id=user_id)
                origin_point = user.point
                origin_obtain_point = user.obtain_point
                new_point = origin_point + instance.point
                new_obtain_point = origin_obtain_point + instance.point
                result = CustomerUserVice.objects.filter(id=user_id, point=origin_point).update(
                    point=new_point,
                    obtain_point=new_obtain_point
                )
                if result == 0:
                    continue
                break
            recoad_data = {}
            recoad_data['customeruservice_id'] = user.id
            recoad_data['operate_type'] = 1
            recoad_data['point_type'] = 4
            recoad_data['point'] = instance.point
            recoad_data['point_balance'] = new_point
            recoad_data['explain'] = '领取积分'
            get_point_record_db_model(user.id).objects.create(**recoad_data)
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)

    def multi_millionaire(self, request):
        queryset = self.get_queryset().filter(activity_type=8).first()
        if not queryset:
            return Response([], status=status.HTTP_200_OK)
        user = self.request.iser
        data = CustomizeActivityLimitModelSerializer(queryset).data
        return Response(data, status=status.HTTP_200_OK)

    def multi_millionaire_detail(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('activity_id', None)
        if not activity_id:
            return Response({'error': '缺少活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            customizeactivity = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_white == 1:
            is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
            if not is_white:
                return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status == 2:
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status != 1:
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
        location = []
        for customizeactivityrules in customizeactivityrules_set:
            location.append(customizeactivityrules.index)
        check_customizeactivityrules_set = customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type__in=[4, 5]))
        data = {}
        check_customizeactivityrules_data = {}
        for check_customizeactivityrules in check_customizeactivityrules_set:
            check_customizeactivityrules_data[check_customizeactivityrules.index] = {
                "index": check_customizeactivityrules.index, "isGrid": 1, "icon": check_customizeactivityrules.icon
            }
        lists = []
        for i in range(56):
            if i in location:
                if i in check_customizeactivityrules_data:
                    lists.append(check_customizeactivityrules_data[i])
                else:
                    lists.append({"index": i,"isGrid": 1,"icon": "https://jinjian.sutpay.cn/image/wyh_micon8.png"})
            else:
                lists.append({"index": i,"isGrid": 0,"icon": ""})
        user_index_data = {}
        user_index_data['customizeactivity_id'] = customizeactivity.id
        user_index_data['customeruservice_id'] = user.id
        user_index_data['index'] = location[0]
        user_index, create = CustomizeActivityUserIndex.objects.get_or_create(defaults=user_index_data, customizeactivity_id=customizeactivity.id, customeruservice_id=user.id)
        data['index'] = user_index.index
        data['lists'] = lists
        data['activity_description'] = customizeactivity.activity_description
        data['id'] = customizeactivity.id
        data['activity_name'] = customizeactivity.activity_name
        data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        date_now = datetime.datetime.now()
        week = date_now.weekday()
        customizeactivitylotteryrules = customizeactivity.customizeactivitylotteryrules
        start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
        end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
        publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
        publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
        if customizeactivitylotteryrules.activity_mode == 1:
            if publish_start_time <= date_now and publish_end_time >= date_now:
                data['status'] = 1
            else:
                data['status'] = 0
            data['time'] = f'每天{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
        else:
            if str(week+1) not in customizeactivitylotteryrules.week_days:
                data['status'] = 0
            else:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    data['status'] = 1
                else:
                    data['status'] = 0
            week_days = customizeactivitylotteryrules.week_days
            week_days = week_days.replace('1', '周一').replace('2', '周二').replace('3', '周三').replace('4', '周四').replace('5', '周五').replace('6', '周六').replace('7', '周日')
            data['time'] = f'逢{week_days}{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
        data['point'] = customizeactivitylotteryrules.point
        if customizeactivitylotteryrules.free_limit == 1:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
            data['free_count'] = join_limit_by_user_count - check_count
        else:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id, open_time__gte=publish_start_time, open_time__lte=publish_end_time).count()
            data['free_count'] = join_limit_by_user_count - check_count
        data['remain_point'] = user.point
        return Response(data, status=status.HTTP_200_OK)

    def throw_dice(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('activity_id', None)
        if not activity_id:
            return Response({'error': '缺少活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            customizeactivity = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_white == 1:
            is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
            if not is_white:
                return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status == 2:
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status != 1:
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)

        date_now = datetime.datetime.now()
        week = date_now.weekday()
        customizeactivitylotteryrules = customizeactivity.customizeactivitylotteryrules
        start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
        end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
        publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
        publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
        if customizeactivitylotteryrules.activity_mode == 1:
            if publish_start_time <= date_now and publish_end_time >= date_now:
                pass
            else:
                return Response({'error': '未到活动时间'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            if str(week+1) not in customizeactivitylotteryrules.week_days:
                return Response({'error': '未到活动时间'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    pass
                else:
                    return Response({'error': '未到活动时间'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivitylotteryrules.free_limit == 1:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id).count()
            free_count = join_limit_by_user_count - check_count
        else:
            join_limit_by_user_count = customizeactivitylotteryrules.join_limit_by_user_count
            check_count = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=customizeactivity.id, open_time__gte=publish_start_time, open_time__lte=publish_end_time).count()
            free_count = join_limit_by_user_count - check_count
        if free_count > 0:
            is_free = 1
        else:
            if user.point < customizeactivitylotteryrules.point:
                return Response({'error': '积分不足'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                is_free = 0
                user_id = user.id
                while True:
                    user = CustomerUserVice.objects.get(id=user_id)
                    origin_point = user.point
                    origin_use_point = user.use_point
                    if origin_point < customizeactivitylotteryrules.point:
                        return Response({'error': '积分不足'}, status=status.HTTP_400_BAD_REQUEST)
                    new_point = origin_point - customizeactivitylotteryrules.point
                    new_use_point = origin_use_point + customizeactivitylotteryrules.point
                    result = CustomerUserVice.objects.filter(id=user_id, point=origin_point).update(
                        point=new_point,
                        use_point=new_use_point
                    )
                    if result == 0:
                        continue
                    break
                recoad_data = {}
                recoad_data['customeruservice_id'] = user.id
                recoad_data['operate_type'] = 2
                recoad_data['point_type'] = 4
                recoad_data['point'] = customizeactivitylotteryrules.point
                recoad_data['point_balance'] = new_point
                recoad_data['explain'] = '参与活动抽奖消耗'
                get_point_record_db_model(user.id).objects.create(**recoad_data)
        customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
        location = []
        for customizeactivityrules in customizeactivityrules_set:
            location.append(customizeactivityrules.index)
        check_customizeactivityrules_set = customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type=5))
        index_count = randint(1, 6)
        check_customizeactivityrules_data = {}
        for check_customizeactivityrules in check_customizeactivityrules_set:
            check_customizeactivityrules_data[check_customizeactivityrules.index] = check_customizeactivityrules.id
        location = location * 2
        user_index_data = {}
        user_index_data['customizeactivity_id'] = customizeactivity.id
        user_index_data['customeruservice_id'] = user.id
        user_index, create = CustomizeActivityUserIndex.objects.get_or_create(defaults=user_index_data, customizeactivity_id=customizeactivity.id, customeruservice_id=user.id)
        index_now = user_index.index
        index_count_begin = location.index(index_now)
        index_count_end = index_count_begin + index_count
        index_end = location[index_count_end]
        user_index.index = index_end
        user_index.save()
        location = location[index_count_begin+1: index_count_end+1]
        if index_end not in check_customizeactivityrules_data:
            data = {}
            data["id"] = 'X'
            identify = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            instance_data = dict()
            instance_data['identify'] = identify
            instance_data['customeruservice_id'] = user.id
            instance_data['gears'] = 1
            instance_data['customizeactivity_id'] = customizeactivity.id
            instance_data['open_status'] = 3
            instance_data['open_time'] = datetime.datetime.now()
            instance_data['is_free'] = is_free
            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
            data["take_id"] = instance.id
            data["amount"] = ''
            data["activity_name"] = ''
            data["msg"] = ''
            data["available_time"] = ''
            data["win_type_str"] = '谢谢参与'
            data["win_type"] = 4
            data["index"] = index_count
            data["index_end"] = index_end
            data["location"] = location
            return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
        else:
            customizeactivityrules_id = check_customizeactivityrules_data[index_end]
            customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
            identify = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            instance_data = dict()
            instance_data['identify'] = identify
            instance_data['customeruservice_id'] = user.id
            instance_data['gears'] = 1
            instance_data['customizeactivity_id'] = customizeactivity.id
            instance_data['is_free'] = is_free
            if customizeactivityrules.prize_type in [1, 2]:
                instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                instance_data['win_type'] = customizeactivityrules.prize_type
            elif customizeactivityrules.prize_type in [3, 6]:
                instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                instance_data['win_type'] = customizeactivityrules.prize_type
            elif customizeactivityrules.prize_type == 5:
                instance_data['point'] = customizeactivityrules.point
                instance_data['win_type'] = customizeactivityrules.prize_type
            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
            if instance.win_type == 4:
                instance.open_status = 3
                instance.open_time = datetime.datetime.now()
                instance.save()
                data = {}
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = ''
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = '谢谢参与'
                data["win_type"] = 4
                data["index"] = index_count
                data["index_end"] = index_end
                data["location"] = location
                return Response({'success': '谢谢参与', 'data': data},status=status.HTTP_200_OK)
            elif instance.win_type in [1, 2]:
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                alidiscountcoupon = instance.alidiscountcoupon
                data = {}
                if alidiscountcoupon.remain_number <= 0:
                    x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                    if x:
                        shuffle(x)
                        alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                        instance.alidiscountcoupon_id = alidiscountcoupon.id
                        instance.save()
                    else:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        data["index"] = index_count
                        data["index_end"] = index_end
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                activity_id = alidiscountcoupon.id
                while True:
                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = alidiscountcoupon.send_count
                    activity_origin_remain_number = alidiscountcoupon.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    if activity_new_remain_number < 0:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        data["index"] = index_count
                        data["index_end"] = index_end
                        data["location"] = location
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                    if result == 0:
                        continue
                    break
                alidiscountcouponinfo_data = {}
                alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                alidiscountcouponinfo_data['level_id'] = instance.level_id
                alidiscountcouponinfo_data['status'] = 0
                alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                alidiscountcouponinfo_data['mobile'] = user.mobile
                alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                alidiscountcouponinfo_data['customeruservice_id'] = user.id
                alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = alidiscountcoupon.amount
                data["activity_name"] = alidiscountcoupon.activity_name
                data["msg"] = alidiscountcoupon.floor_amount
                data["available_time"] = f'{alidiscountcoupon.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{alidiscountcoupon.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["index"] = index_count
                data["index_end"] = index_end
                data["location"] = location
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
            elif instance.win_type == 5:
                data = {}
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = instance.point
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = f''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["index"] = index_count
                data["index_end"] = index_end
                data["location"] = location
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
            else:
                data = {}
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                cashactivity = instance.cashactivity
                cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                if cashactivityrule.amount > cashactivity.remain_amount:
                    instance.open_status = 3
                    instance.win_type = 4
                    instance.open_time = datetime.datetime.now()
                    instance.save()
                    data['id'] = customizeactivityrules_id
                    data['take_id'] = instance.id
                    data["amount"] = ''
                    data["activity_name"] = ''
                    data["msg"] = ''
                    data["available_time"] = ''
                    data["win_type_str"] = '谢谢参与'
                    data["win_type"] = 4
                    data["index"] = index_count
                    data["index_end"] = index_end
                    data["location"] = location
                    return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                amount = cashactivityrule.amount
                activity_id = cashactivity.id
                while True:
                    activity = CashActivity.objects.get(id=activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    if activity_origin_remain_amount < amount:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        data["index"] = index_count
                        data["index_end"] = index_end
                        data["location"] = location
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                    if result == 0:
                        continue
                    break
                date_now = datetime.datetime.now()
                activity_data = {}
                activity_data['amount'] = amount
                activity_data['create_time'] = date_now
                activity_data['cash_activity_id'] = activity.id
                activity_data['level_id'] = instance.level_id
                activity_data['state'] = 1
                identify = random_str()
                nonce_str = random_str()
                activity_data['identify'] = identify
                activity_data['nonce_str'] = nonce_str
                activity_data['desc'] = activity.name
                activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                activity_data['customeruservice_id'] = user.id
                activity_data['mobile'] = user.mobile
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                instance.cashactivitydata_id = activity_dat.id
                instance.amount = amount
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = amount
                data["activity_name"] = cashactivity.name
                data["msg"] = ''
                data["available_time"] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["index"] = index_count
                data["index_end"] = index_end
                data["location"] = location
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)

    def recommend_activity(self, request):
        user = self.request.iser
        is_now = self.request.query_params.get('is_now', None)
        today = datetime.datetime.now()
        if not is_now:
            activity_set = CustomizeActivity.objects.filter(activity_type=9)
        else:
            activity_set = CustomizeActivity.objects.filter(activity_type=9, available_begin_time__lte=today, available_end_time__gte=today)
        total_count = CustomerUserViceInviterRecord.objects.filter(inviter_id=user.id).count()
        data = []
        for activity in activity_set:
            activity_info = {}
            draw_info = {}
            activity_info['id'] = activity.id
            activity_info['activity_name'] = activity.activity_name
            activity_info['issue'] = activity.activity_name[-3:]
            activity_info['available_begin_time'] = activity.available_begin_time.strftime("%Y.%m.%d")
            activity_info['available_end_time'] = activity.available_end_time.strftime("%Y.%m.%d")
            activity_info['inviter_begin_time'] = activity.available_begin_time.strftime("%Y-%m-%d")
            activity_info['inviter_end_time'] = activity.available_end_time.strftime("%Y-%m-%d")
            if activity.activity_status == 3:
                if activity.available_begin_time < today:
                    activity.activity_status = 1
                    activity.save()
            if activity.activity_status == 1:
                if activity.available_end_time < today:
                    activity.activity_status = 2
                    activity.save()
            activity_info['activity_status'] = activity.activity_status
            inviter_count = CustomerUserViceInviterRecord.objects.filter(inviter_id=user.id, inviter_time__gte=activity.available_begin_time, inviter_time__lte=activity.available_end_time).count()
            activity_info['total_count'] = total_count
            activity_info['inviter_count'] = inviter_count
            activity_info['received_time'] = ''
            customize_activity_lottery_rules_user_free_count = CustomizeActivityLotteryRulesUserFreeCount.objects.filter(customizeactivity_id=activity.id, customeruservice_id=user.id).first()
            if not customize_activity_lottery_rules_user_free_count:
                # inviter_count = CustomerUserVice.objects.filter(inviter_id=user.id, inviter_time__gte=activity.available_begin_time, inviter_time__lte=activity.available_end_time).count()
                if inviter_count >=3:
                    customize_activity_lottery_rules_user_free_count_data = {}
                    customize_activity_lottery_rules_user_free_count_data['customizeactivity_id'] = activity.id
                    customize_activity_lottery_rules_user_free_count_data['customeruservice_id'] = user.id
                    customize_activity_lottery_rules_user_free_count_data['count'] = 1
                    CustomizeActivityLotteryRulesUserFreeCount.objects.get_or_create(customizeactivity_id=activity.id,
                                                                              customeruservice_id=user.id, defaults=customize_activity_lottery_rules_user_free_count_data)
                    activity_info['draw_status'] = 1
                else:
                    activity_info['draw_status'] = 0
            else:
                customizeactivityflipcards = CustomizeActivityFlipCARDS.objects.filter(is_free=1, customeruservice_id=user.id, customizeactivity_id=activity.id).first()
                if not customizeactivityflipcards:
                    activity_info['draw_status'] = 1
                else:
                    if customizeactivityflipcards.open_status in [2, 6]:
                        activity_info['draw_status'] = 2
                        draw_info = CustomizeActivityFlipCARDSListModelSerializer(customizeactivityflipcards).data
                    elif customizeactivityflipcards.open_status == 4:
                        activity_info['draw_status'] = 3
                        activity_info['received_time'] = customizeactivityflipcards.received_time.strftime("%Y-%m-%d %H:%M:%S")
                        draw_info = CustomizeActivityFlipCARDSListModelSerializer(customizeactivityflipcards).data
                    else:
                        activity_info['draw_status'] = 3
            activity_info['draw_info'] = draw_info
            activity_info['activity_description'] = activity.activity_description
            data.append(activity_info)
        return Response(data, status=status.HTTP_200_OK)

    def benben_customizeactivity(self, request):
        user = self.request.iser
        customizeactivity_id = self.request.query_params.get('activity_id', None)
        if not customizeactivity_id:
            return Response({'error': '缺少活动参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            customizeactivity = self.get_queryset().get(id=customizeactivity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.id != 115:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        benbenorder_set = CustomizeActivityBenBenOrder.objects.filter(customeruservice_id=user.id, open_status=1, customizeactivityflipcards_id__isnull=True)
        for benben_order in benbenorder_set:
            date_now = benben_order.pay_time
            customizeactivity = CustomizeActivity.objects.get(id=customizeactivity_id)
            if date_now < customizeactivity.available_begin_time or date_now > customizeactivity.available_end_time:
                benben_order.open_status = 5
                benben_order.save()
            else:
                total_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customeruservice_id=user.id,win_type=6).count()
                if total_draws < 3:
                    next_month = (date_now.month % 12) + 1
                    if next_month == 1:
                        next_month_first_day = date_now.replace(day=1, month=next_month, year=date_now.year + 1)
                    else:
                        next_month_first_day = date_now.replace(day=1, month=next_month)
                    this_month = next_month_first_day - datetime.timedelta(days=1)
                    this_month_first_day = this_month.strftime('%Y-%m-01 00:00:00')
                    this_month_last_day = this_month.strftime('%Y-%m-%d 23:59:59')
                    month_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customeruservice_id=user.id,win_type=6,pay_time__gte=this_month_first_day,pay_time__lte=this_month_last_day).count()
                    if month_draws < 1:
                        check_customizeactivityrules_set = customizeactivity.customizeactivityrules_set.filter(
                            Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0))
                        check_customizeactivityrules_id_list = []
                        for check_customizeactivityrules in check_customizeactivityrules_set:
                            if check_customizeactivityrules.is_limit_by_day == 1:
                                day_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivityrules_id=check_customizeactivityrules.id,pay_time__gte=date_now.strftime('%Y-%m-%d 00:00:00'),pay_time__lte=date_now.strftime('%Y-%m-%d 23:59:59')).count()
                                if day_draws < check_customizeactivityrules.limit_by_day_count:
                                    check_customizeactivityrules_id_list.append(check_customizeactivityrules.id)
                        if not check_customizeactivityrules_id_list:
                            identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ","").replace(".", "")}{"%06d" % randint(0, 999999)}'
                            instance_data = dict()
                            instance_data['identify'] = identify
                            instance_data['customeruservice_id'] = user.id
                            instance_data['gears'] = 1
                            instance_data['customizeactivity_id'] = customizeactivity.id
                            instance_data['open_status'] = 1
                            instance_data['open_time'] = None
                            instance_data['pay_time'] = date_now
                            instance_data['is_free'] = 0
                            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                            benben_order.customizeactivityflipcards_id = instance.id
                            benben_order.save()
                        else:
                            customizeactivityrules_id = random.choices(check_customizeactivityrules_id_list, k=1)[0]
                            customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
                            identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                            instance_data = dict()
                            instance_data['identify'] = identify
                            instance_data['customeruservice_id'] = user.id
                            instance_data['gears'] = 1
                            instance_data['customizeactivity_id'] = customizeactivity.id
                            instance_data['customizeactivityrules_id'] = customizeactivityrules.id
                            instance_data['pay_time'] = date_now
                            instance_data['is_free'] = 0
                            if customizeactivityrules.prize_type in [1, 2]:
                                instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                                instance_data['win_type'] = customizeactivityrules.prize_type
                            elif customizeactivityrules.prize_type in [3, 6]:
                                instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                                instance_data['win_type'] = customizeactivityrules.prize_type
                            elif customizeactivityrules.prize_type == 5:
                                instance_data['point'] = customizeactivityrules.point
                                instance_data['win_type'] = customizeactivityrules.prize_type
                            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                            benben_order.customizeactivityflipcards_id = instance.id
                            benben_order.save()
                            cashactivity = instance.cashactivity
                            cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id,is_delete=0).first()
                            amount = cashactivityrule.amount
                            activity_id = cashactivity.id
                            while True:
                                activity = CashActivity.objects.get(id=activity_id)
                                activity_origin_take_amount = activity.take_amount
                                activity_origin_remain_amount = activity.remain_amount
                                activity_new_take_amount = activity_origin_take_amount + amount
                                activity_new_remain_amount = activity_origin_remain_amount - amount
                                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,remain_amount=activity_origin_remain_amount,id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                                if result == 0:
                                    continue
                                break
                            date_now = datetime.datetime.now()
                            activity_data = {}
                            activity_data['amount'] = amount
                            activity_data['create_time'] = date_now
                            activity_data['cash_activity_id'] = activity.id
                            activity_data['level_id'] = instance.level_id
                            activity_data['state'] = 1
                            identify = random_str()
                            nonce_str = random_str()
                            activity_data['identify'] = identify
                            activity_data['nonce_str'] = nonce_str
                            activity_data['desc'] = activity.name
                            activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                            activity_data['customeruservice_id'] = user.id
                            activity_data['mobile'] = user.mobile
                            activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                            instance.cashactivitydata_id = activity_dat.id
                            instance.amount = amount
                            instance.save()
                    else:
                        identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ","").replace(".", "")}{"%06d" % randint(0, 999999)}'
                        instance_data = dict()
                        instance_data['identify'] = identify
                        instance_data['customeruservice_id'] = user.id
                        instance_data['gears'] = 1
                        instance_data['customizeactivity_id'] = customizeactivity.id
                        instance_data['open_status'] = 1
                        instance_data['open_time'] = None
                        instance_data['pay_time'] = date_now
                        instance_data['is_free'] = 0
                        instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                        benben_order.customizeactivityflipcards_id = instance.id
                        benben_order.save()
                else:
                    identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ","").replace(".", "")}{"%06d" % randint(0, 999999)}'
                    instance_data = dict()
                    instance_data['identify'] = identify
                    instance_data['customeruservice_id'] = user.id
                    instance_data['gears'] = 1
                    instance_data['customizeactivity_id'] = customizeactivity.id
                    instance_data['open_status'] = 1
                    instance_data['open_time'] = None
                    instance_data['pay_time'] = date_now
                    instance_data['is_free'] = 0
                    instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                    benben_order.customizeactivityflipcards_id = instance.id
                    benben_order.save()
        customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
        data = {}
        lists = CustomizeActivityRulesListModelSerializer(customizeactivityrules_set, many=True).data
        data['lists'] = lists
        data['activity_description'] = customizeactivity.activity_description
        data['id'] = customizeactivity.id
        data['activity_name'] = customizeactivity.activity_name
        data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        count = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, customeruservice_id=user.id, open_status=1).count()
        data['count'] = count
        return Response(data, status=status.HTTP_200_OK)

    def benben_lucky_draw(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('activity_id', None)
        if not activity_id:
            return Response({'error': '缺少必传参数', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            customizeactivity = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivityflipcards = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=activity_id, customeruservice_id=user.id, open_status=1).first()
        if not customizeactivityflipcards:
            return Response({'error': '您暂无抽奖机会,使用微邮付本对本付款500元以上便可获得一次抽奖机会'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        if customizeactivityflipcards.win_type == 4:
            customizeactivityflipcards.open_status = 3
            customizeactivityflipcards.open_time = datetime.datetime.now()
            customizeactivityflipcards.mobile = user.mobile
            customizeactivityflipcards.save()
            data['id'] = 690
            data["take_id"] = customizeactivityflipcards.id
            data["amount"] = ''
            data["activity_name"] = ''
            data["msg"] = ''
            data["available_time"] = ''
            data["win_type_str"] = '谢谢参与'
            data["win_type"] = 4
            return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
        else:
            customizeactivityflipcards.open_status = 2
            customizeactivityflipcards.open_time = datetime.datetime.now()
            customizeactivityflipcards.mobile = user.mobile
            customizeactivityflipcards.save()
            cashactivity = customizeactivityflipcards.cashactivity
            data['id'] = customizeactivityflipcards.customizeactivityrules_id
            data['take_id'] = customizeactivityflipcards.id
            data["amount"] = customizeactivityflipcards.amount
            data["activity_name"] = cashactivity.name
            data["msg"] = ''
            data["available_time"] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            data["win_type_str"] = customizeactivityflipcards.get_win_type_display()
            data["win_type"] = customizeactivityflipcards.win_type
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)

    def share_customizeactivity(self, request):
        user = self.request.iser
        customizeactivity_id = 126
        customizeactivity = CustomizeActivity.objects.filter(id=customizeactivity_id, available_end_time__gte=datetime.datetime.now(), activity_status=1).first()
        if not customizeactivity:
            return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        check_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity_id).first()
        if check_white:
            if check_white.rule_id:
                customizeactivityrules_set = customizeactivity.customizeactivityrules_set.exclude(id=756)
            else:
                customizeactivityrules_set = customizeactivity.customizeactivityrules_set.exclude(id=757)
        else:
            customizeactivityrules_set = customizeactivity.customizeactivityrules_set.exclude(id=757)
        data = {}
        lists = CustomizeActivityRulesListModelSerializer(customizeactivityrules_set, many=True).data
        data['lists'] = lists
        data['activity_description'] = customizeactivity.activity_description
        data['id'] = customizeactivity.id
        data['activity_name'] = customizeactivity.activity_name
        data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        if not check_white:
            data['count'] = 0
        else:
            check_flip = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, mobile=user.mobile).first()
            if not check_flip:
                data['count'] = 1
            else:
                data['count'] = 0
        return Response(data, status=status.HTTP_200_OK)

    def share_lucky_draw(self, request):
        user = self.request.iser
        customizeactivity_id = 126
        customizeactivity = CustomizeActivity.objects.filter(id=customizeactivity_id, available_end_time__gte=datetime.datetime.now(), activity_status=1).first()
        if not customizeactivity:
            return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        check_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity_id).first()
        if not check_white:
            return Response({'error': '您无抽奖机会'}, status=status.HTTP_400_BAD_REQUEST)
        check_flip = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, mobile=user.mobile).first()
        if check_flip:
            return Response({'error': '您已抽过奖'}, status=status.HTTP_400_BAD_REQUEST)
        '''
        751:邮享登录1元883
        752:邮享登录1.5元882
        753:邮享登录8.8元881
        754:邮享登录4.88元880
        755:邮享登录7.88元879
        756:邮享登录88元878  23
        757:邮享登录88元878  限定27
        '''
        if check_white.rule_id:
            customizeactivityrules_id = check_white.rule_id
        else:
            customizeactivityrules_id = 756
            check_flip_count = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customizeactivityrules_id=756).count()
            if check_flip_count >= 23:
                customizeactivityrules_id = 755
                check_flip_count = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customizeactivityrules_id=755).count()
                if check_flip_count >= 587:
                    customizeactivityrules_id = 754
                    check_flip_count = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customizeactivityrules_id=754).count()
                    if check_flip_count >= 948:
                        customizeactivityrules_id = 753
                        check_flip_count = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customizeactivityrules_id=753).count()
                        if check_flip_count >= 10:
                            customizeactivityrules_id = 752
                            check_flip_count = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id,customizeactivityrules_id=752).count()
                            if check_flip_count >= 820:
                                customizeactivityrules_id = 751
        date_now = datetime.datetime.now()
        customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
        identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        instance_data = dict()
        instance_data['identify'] = identify
        instance_data['customeruservice_id'] = user.id
        instance_data['open_status'] = 2
        instance_data['open_time'] = date_now
        instance_data['gears'] = 1
        instance_data['customizeactivity_id'] = customizeactivity.id
        instance_data['customizeactivityrules_id'] = customizeactivityrules.id
        instance_data['is_free'] = 0
        instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
        instance_data['win_type'] = customizeactivityrules.prize_type
        instance_data['mobile'] = user.mobile
        instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
        cashactivity = instance.cashactivity
        cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
        amount = cashactivityrule.amount
        activity_id = cashactivity.id
        while True:
            activity = CashActivity.objects.get(id=activity_id)
            activity_origin_take_amount = activity.take_amount
            activity_origin_remain_amount = activity.remain_amount
            activity_new_take_amount = activity_origin_take_amount + amount
            activity_new_remain_amount = activity_origin_remain_amount - amount
            result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
            if result == 0:
                continue
            break
        activity_data = {}
        activity_data['amount'] = amount
        activity_data['create_time'] = date_now
        activity_data['cash_activity_id'] = activity.id
        activity_data['level_id'] = instance.level_id
        activity_data['state'] = 1
        identify = random_str()
        nonce_str = random_str()
        activity_data['identify'] = identify
        activity_data['nonce_str'] = nonce_str
        activity_data['desc'] = activity.name
        activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
        activity_data['customeruservice_id'] = user.id
        activity_data['mobile'] = user.mobile
        activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
        instance.cashactivitydata_id = activity_dat.id
        instance.amount = amount
        instance.save()
        data = {}
        data['id'] = instance.customizeactivityrules_id
        data['take_id'] = instance.id
        data["amount"] = instance.amount
        data["activity_name"] = cashactivity.name
        data["msg"] = ''
        data["available_time"] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        data["win_type_str"] = instance.get_win_type_display()
        data["win_type"] = instance.win_type
        return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)

    def allow_couponbag(self, request):
        identify = self.request.query_params.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            qrcode = CustomizeActivityQRCode.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivity_level = qrcode.customizeactivity_level
        customizeactivity = customizeactivity_level.customizeactivity
        data = {}
        data['activity_name'] = customizeactivity.activity_name
        data['publish_end_time'] = customizeactivity.available_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        data['activity_description'] = customizeactivity.activity_description
        data['qrcode_state'] = qrcode.qrcode_state
        data['is_need_auth'] = customizeactivity.is_need_auth
        data['is_psbc_card'] = customizeactivity.is_psbc_card
        customizeactivityrules_set = CustomizeActivityRules.objects.filter(customizeactivity_id=customizeactivity.id)
        coupon_data = []
        for customizeactivityrules in customizeactivityrules_set:
            rules_data = {}
            rules_data['floor_amount'] = customizeactivityrules.alidiscountcoupon.floor_amount
            rules_data['coupon_channel'] = customizeactivityrules.alidiscountcoupon.coupon_channel
            rules_data['count'] = customizeactivityrules.count
            coupon_data.append(rules_data)
        data['coupon_data'] = coupon_data
        return Response(data, status=status.HTTP_200_OK)

    def receive_couponbag(self, request):
        user = self.request.iser
        if user.is_mobile != 1:
            return Response({'error': '请先绑定手机号'}, status=status.HTTP_400_BAD_REQUEST)
        identify = self.request.data.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            qrcode = CustomizeActivityQRCode.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        if qrcode.qrcode_state != 1:
            return Response({'error': '二维码已被领取'}, status=status.HTTP_400_BAD_REQUEST)
        qrcode.qrcode_state = 2
        qrcode.save()
        customizeactivity_level = qrcode.customizeactivity_level
        if customizeactivity_level.remain_number <= 0:
            return Response({'error': '活动额度已派完'}, status=status.HTTP_400_BAD_REQUEST)
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                customizeactivity_level_id = customizeactivity_level.id
                while True:
                    customizeactivity_level = CustomizeActivityLevel.objects.get(id=customizeactivity_level_id)
                    origin_take_number = customizeactivity_level.take_number
                    origin_remain_number = customizeactivity_level.remain_number
                    origin_receive_number = customizeactivity_level.receive_number
                    if origin_remain_number <= 0:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '活动额度已派完'}, status=status.HTTP_400_BAD_REQUEST)
                    new_take_number = origin_take_number + 1
                    new_remain_number = origin_remain_number - 1
                    new_receive_number = origin_receive_number + 1
                    result = CustomizeActivityLevel.objects.filter(id=customizeactivity_level_id, take_number=origin_take_number, receive_number=origin_receive_number, remain_number=origin_remain_number).update(take_number=new_take_number, receive_number=new_receive_number, remain_number=new_remain_number)
                    if result == 0:
                        continue
                    break
                today = datetime.datetime.now()
                defaults = {}
                defaults['customeruservice_id'] = user.id
                defaults['open_status'] = 2
                defaults['identify'] = qrcode.out_biz_no
                defaults['received_time'] = today
                defaults['open_time'] = qrcode.gmt_distributed
                defaults['pay_time'] = today
                defaults['gears'] = 1
                defaults['win_type'] = 8
                defaults['customizeactivity_id'] = customizeactivity_level.customizeactivity_id
                defaults['level_id'] = qrcode.companyuser.level_id
                defaults['mobile'] = user.mobile
                defaults['companyuser_id'] = qrcode.companyuser_id
                instance, create = CustomizeActivityFlipCARDS.objects.get_or_create(defaults=defaults, identify=qrcode.out_biz_no)
            except:
                transaction.savepoint_rollback(save_id)
                return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            distribute_couponbag.delay({"filp_id": instance.id})
            return Response({'success': '领取成功'}, status=status.HTTP_200_OK)


class CustomizeActivityFlipCARDSModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)

    def get_serializer_class(self):
        if self.action == 'list':
            return CustomizeActivityFlipCARDSListModelSerializer
        else:
            return CustomizeActivityFlipCARDSRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        if self.action == 'list':
            customizeactivity_id = self.request.query_params.get('activity_id', None)
            if customizeactivity_id:
                queryset = CustomizeActivityFlipCARDS.objects.filter(customeruservice_id=user.id, open_status__in=[2, 4, 6], customizeactivity_id=customizeactivity_id)
            else:
                queryset = CustomizeActivityFlipCARDS.objects.filter(customeruservice_id=user.id, open_status__in=[2, 4, 6])
        else:
            queryset = CustomizeActivityFlipCARDS.objects.filter(customeruservice_id=user.id)
        return queryset.order_by('-id')


class MerchantModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )
    filter_class = MerchantFilter

    def get_queryset(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        if not all([longitude, latitude]):
            queryset = Merchant.objects.filter(is_mall=2)
        else:
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = Merchant.objects.filter(latitude__isnull=False, is_mall=2).exclude(latitude='').annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
        return queryset.exclude(id__in=[481])

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())
        pk = self.kwargs['pk']
        try:
            obj = queryset.get(Q(id=pk) | Q(wyfMerchantID=str(pk)))
        except:
            raise serializers.ValidationError({'error': '找不到！'})
        return obj

    def get_serializer_class(self):
        if self.action == 'list':
            return MerchantListModelSerializer
        else:
            return MerchantRetrieveModelSerializer

    def get_serializer_context(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        return {'longitude': longitude, 'latitude': latitude}

    def merchant_info(self, request):
        user = self.request.iser
        shop_id = self.request.query_params.get('shop_id', None)
        if not shop_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if len(shop_id) == 32:
            try:
                merchant = Merchant.objects.get(ruiyinxinMerchantID=shop_id)
            except:
                return Response({'error': '无效商户参数'}, status=status.HTTP_400_BAD_REQUEST)
            is_c_bind = 0
        else:
            try:
                instance = MerchantBusinessQRCode.objects.get(sn=shop_id)
                merchant = instance.merchant
                if not merchant:
                    return Response({'error': '商圈码尚未绑定商户'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                return Response({'error': '无效商户参数'}, status=status.HTTP_400_BAD_REQUEST)
            is_c_bind = instance.is_c_bind
        data = {}
        if user.is_psbc_card != 0:
            data['is_check_card'] = 0
        else:
            longitude = self.request.query_params.get('longitude', None)
            latitude = self.request.query_params.get('latitude', None)
            merchant_longitude = merchant.longitude
            merchant_latitude = merchant.latitude
            if all([longitude, latitude, merchant_longitude, merchant_latitude]):
                try:
                    distance = geodesic((merchant_latitude, merchant_longitude), (latitude, longitude)).m
                    if distance <= 1000:
                        bindcardorder = BindCardOrder.objects.filter(customeruservice_id=user.id,customizeactivity__available_end_time__gte=datetime.datetime.now()).exclude(prize_status=5).first()
                        if not bindcardorder:
                            check_activity = CustomizeActivity.objects.filter(activity_type=5, activity_status=1, available_end_time__gte=datetime.datetime.now()).first()
                            if not check_activity:
                                data['is_check_card'] = 0
                            else:
                                data['is_check_card'] = 1
                        else:
                            data['is_check_card'] = 1
                    else:
                        data['is_check_card'] = 0
                except:
                    data['is_check_card'] = 0
            else:
                data['is_check_card'] = 0
        data['is_subscribe'] = user.is_subscribe
        merchant_info = {}
        merchantimage_set_data = []
        try:
            merchantimage_set = merchant.merchantimage_set.all()
            for merchantimage in merchantimage_set:
                merchantimage_set_data.append(merchantimage.image.url)
        except:
            pass
        merchant_info['merchantimage_set'] = merchantimage_set_data
        merchant_info['short_name'] = merchant.short_name
        merchant_info['store_address'] = merchant.store_address
        merchant_info['managermobile'] = merchant.managermobile
        merchant_info['id'] = merchant.id
        if merchant.store_header_copy:
            merchant_info['store_header_copy'] = merchant.store_header_copy.url
        else:
            merchant_info['store_header_copy'] = 'https://circle.sutpay.cn/default_merchant_logo.jpg'
        merchant_info['business_qrcode'] = shop_id
        merchant_info['is_c_bind'] = is_c_bind
        data['merchant_info'] = merchant_info
        MerchantBusinessQRCodeVisit.objects.create(
            customeruservice_id=user.id,
            qrcode_id=instance.id
        )
        try:
            inviter_id = instance.customeruservice_id
            if inviter_id:
                check_inviter_recode = CustomerUserViceInviterRecord.objects.filter(customeruservice_id=user.id, inviter_id=inviter_id).first()
                if not check_inviter_recode:
                    inviter_recode_data = {}
                    inviter_recode_data['customeruservice_id'] = user.id
                    inviter_recode_data['qrcode_id'] = instance.id
                    inviter_recode_data['inviter_id'] = inviter_id
                    inviter_recode, create = CustomerUserViceInviterRecord.objects.get_or_create(defaults=inviter_recode_data, customeruservice_id=user.id, inviter_id=inviter_id)
                    if create:
                        instance.inviter_total_count += 1
                        instance.save()
        except:
            pass
        today = datetime.datetime.now()
        activity = CustomizeActivity.objects.filter(activity_type=9, available_begin_time__lte=today, available_end_time__gte=today).first()
        if activity:
            merchant_info['available_begin_time'] = activity.available_begin_time.strftime("%Y.%m.%d")
            merchant_info['available_end_time'] = activity.available_end_time.strftime("%Y.%m.%d")
            merchant_info['inviter_begin_time'] = activity.available_begin_time.strftime("%Y-%m-%d")
            merchant_info['inviter_end_time'] = activity.available_end_time.strftime("%Y-%m-%d")
        else:
            merchant_info['available_begin_time'] = ''
            merchant_info['available_end_time'] = ''
            merchant_info['inviter_begin_time'] = ''
            merchant_info['inviter_end_time'] = ''
        return Response(data, status=status.HTTP_200_OK)

    def check_shopkeeper(self, request):
        user = self.request.iser
        code = self.request.data.get('code', None)
        encryptedData = self.request.data.get('encryptedData', None)
        iv = self.request.data.get('iv', None)
        business_qrcode = self.request.data.get('business_qrcode', None)
        if not all([code, encryptedData, iv, business_qrcode]):
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = MerchantBusinessQRCode.objects.get(sn=business_qrcode)
            if instance.is_bind == 0:
                return Response({'error': '商圈码尚未绑定商户'}, status=status.HTTP_400_BAD_REQUEST)
            merchant = instance.merchant
        except:
            return Response({'error': '无效商户参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.is_c_bind == 1:
            return Response({'error': '商圈码尚已绑定店主'}, status=status.HTTP_400_BAD_REQUEST)
        appid = settings.CUSTOMER_APP_ID_WYH
        secret = settings.CUSTOMER_APP_SECRET_WYH
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'
        response = requests.get(url)
        data_dict = json.loads(response.content)
        if 'errcode' in data_dict:
            return Response({'error': str(data_dict['errcode']) + '错误,请联系管理员!'}, status=status.HTTP_400_BAD_REQUEST)
        session_key = data_dict['session_key']
        openid = data_dict['openid']
        pc = WXBizDataCrypt(appid, session_key)
        try:
            mobile = pc.decrypt(encryptedData, iv)['phoneNumber']
        except Exception as e:
            logging.error(e)
            print(e)
            return Response({'error': '获取手机号错误,请重新获取!'}, status=status.HTTP_400_BAD_REQUEST)
        customeruser, create = CustomerUser.objects.get_or_create(mobile=mobile, defaults={'mobile': mobile, 'create_time': datetime.datetime.now()})
        if create:
            AliDiscountCouponInfo.objects.filter(Q(mobile=mobile, customer_user__isnull=True)).update(customer_user_id=customeruser.id)
        if not customeruser.wyh_openid:
            customeruser.wyh_openid = openid
            customeruser.save()
        CustomerUserViceRelation.objects.get_or_create(customeruser_id=customeruser.id, customeruservice_id=user.id, defaults={"customeruser_id": customeruser.id, "customeruservice_id": user.id})
        user.is_mobile = 1
        user.customeruser_id = customeruser.id
        user.mobile = customeruser.mobile
        user.save()
        merchant_info = {}
        merchant_info['short_name'] = merchant.short_name
        merchant_info['store_address'] = merchant.store_address
        if merchant.store_header_copy:
            merchant_info['store_header_copy'] = merchant.store_header_copy.url
        else:
            merchant_info['store_header_copy'] = 'https://circle.sutpay.cn/default_merchant_logo.jpg'
        merchant_info['business_qrcode'] = business_qrcode
        if merchant.managermobile == mobile:
            return Response({'status': 1, 'merchant_info': merchant_info}, status=status.HTTP_200_OK)
        else:
            return Response({'status': 0, 'merchant_info': merchant_info, 'mobile': merchant.managermobile[-4:]}, status=status.HTTP_200_OK)

    def bind_shopkeeper(self, request):
        user = self.request.iser
        business_qrcode = self.request.data.get('business_qrcode', None)
        if not business_qrcode:
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = MerchantBusinessQRCode.objects.get(sn=business_qrcode)
            if instance.is_bind == 0:
                return Response({'error': '商圈码尚未绑定商户'}, status=status.HTTP_400_BAD_REQUEST)
            merchant = instance.merchant
        except:
            return Response({'error': '无效商户参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.is_c_bind == 1:
            return Response({'error': '商圈码尚已绑定店主'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.managermobile != user.mobile:
            return Response({'error': '用户信息与商户信息不匹配,不能绑定'}, status=status.HTTP_400_BAD_REQUEST)
        instance.is_c_bind = 1
        instance.customeruservice_id = user.id
        instance.c_bind_time = datetime.datetime.now()
        instance.save()
        try:
            CustomerUserViceInviterRecord.objects.filter(qrcode_id=instance.id).update(inviter_id=user.id)
        except:
            pass
        bindcardorder_set = BindCardOrder.objects.filter(business_qrcode=business_qrcode, is_exchange=0).exclude(bank_type_sign=3)
        for bindcardorder in bindcardorder_set:
            inviter_id = instance.customeruservice_id
            while True:
                inviter_user = CustomerUserVice.objects.get(id=inviter_id)
                origin_point = inviter_user.point
                origin_obtain_point = inviter_user.obtain_point
                new_point = origin_point + Decimal('50')
                new_obtain_point = origin_obtain_point + Decimal('50')
                result = CustomerUserVice.objects.filter(id=inviter_id, point=origin_point).update(
                    point=new_point,
                    obtain_point=new_obtain_point
                )
                if result == 0:
                    continue
                break
            recoad_data = {}
            recoad_data['customeruservice_id'] = inviter_user.id
            recoad_data['operate_type'] = 1
            recoad_data['point_type'] = 3
            recoad_data['point'] = + Decimal('50')
            recoad_data['point_balance'] = new_point
            recoad_data['explain'] = '邀请新用户参与验卡'
            get_point_record_db_model(inviter_user.id).objects.create(**recoad_data)
            bindcardorder.is_exchange = 1
            bindcardorder.save()
            customeruservice = bindcardorder.customeruservice
            customeruservice.is_first = 0
            customeruservice.inviter_id = inviter_id
            customeruservice.inviter_time = bindcardorder.success_time
            customeruservice.save()
            try:
                CustomerUserViceInviterRecord.objects.filter(customeruservice_id=customeruservice.id, qrcode_id=instance.id).update(inviter_time=bindcardorder.success_time, is_inviter=1)
            except:
                pass
        return Response({'success': '绑定成功'}, status=status.HTTP_200_OK)

    def business_district(self, request):
        return render(request, 'wyh_zfb_waring.html')
        shop_id = self.request.query_params.get('shop_id', None)
        if not shop_id:
            return render(request, 'wyh_zfb_waring.html')
        try:
            instance = MerchantBusinessQRCode.objects.get(sn=shop_id)
            level = instance.level
            if not level:
                return render(request, 'wyh_zfb_waring.html')
        except:
            return render(request, 'wyh_zfb_waring.html')
        city_id = level.city_id
        if city_id not in [8834, 8700, 8845]:
            return render(request, 'wyh_zfb_waring.html')
        else:
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
            print(ip)
            MerchantBusinessQRCodeVisit1.objects.create(
                ip=ip,
                qrcode_id=instance.id
            )
            return render(request, 'wyh_zfb_add.html')

    def alipay_district(self, request):
        HTTP_USER_AGENT = self.request.environ['HTTP_USER_AGENT']
        if 'WeChat' in HTTP_USER_AGENT or 'MicroMessenger' in HTTP_USER_AGENT:
            return render(request, 'wx_zfb_add_error.html')
        else:
            return render(request, 'wyh_zfb_add.html')


class NewYearsShoppingFestivalElectModelViewSet(ModelViewSet):

    pagination_class = MyPage
    queryset = NewYearsShoppingFestivalElect.objects.exclude(activity_state=0).order_by('-id')
    serializer_class = NewYearsShoppingFestivalElectListModelSerializer

    def get_serializer_context(self):
        user = self.request.iser
        return {'user': user}


class NewYearsShoppingFestivalElectProductModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('product_title',)

    def get_queryset(self):
        elect_id = self.request.query_params.get('elect_id', None)
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        queryset = NewYearsShoppingFestivalElectProduct.objects.filter(is_match=1)
        if elect_id:
            queryset = queryset.filter(elect_id=elect_id)
        if longitude and latitude:
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = queryset.objects.annotate(distance=sql).order_by('distance')
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return NewYearsShoppingFestivalElectProductListModelSerializer
        else:
            return NewYearsShoppingFestivalElectProductRetrieveModelSerializer

    def get_serializer_context(self):
        user = self.request.iser
        return {'user': user}

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        today = datetime.datetime.today().strftime('%Y%m%d')
        identification = f'{today}{"%06d" % instance.id}{"%06d" % user.id}'
        identification1 = f'{today}{"%06d" % user.id}'
        check_product = NewYearsShoppingFestivalElectProductLike.objects.filter(identification=identification)
        if check_product:
            return Response({'error': '当天不可对同一作品重复投票'}, status=status.HTTP_400_BAD_REQUEST)
        product_count = NewYearsShoppingFestivalElectProductLike.objects.filter(day=identification1).count()
        if product_count >= 5:
            return Response({'error': '今天的投票机会已用完'}, status=status.HTTP_400_BAD_REQUEST)
        instance_id = instance.id
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                while True:
                    instance = NewYearsShoppingFestivalElectProduct.objects.get(id=instance_id)
                    origin_like_count = instance.like_count
                    new_like_count = origin_like_count + 1
                    result = NewYearsShoppingFestivalElectProduct.objects.filter(like_count=origin_like_count, id=instance_id).update(like_count=new_like_count)
                    if result == 0:
                        continue
                    break
                NewYearsShoppingFestivalElectProductLike.objects.create(
                    product_id=instance.id,
                    customeruservice_id=user.id,
                    identification=identification,
                    day=identification1
                )
                transaction.savepoint_commit(save_id)
                return Response({'success': '投票成功'}, status=status.HTTP_200_OK)
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '投票失败,请重新操作'}, status=status.HTTP_400_BAD_REQUEST)

    def leaderboard(self, request):
        user = self.request.iser
        elect_id = self.request.query_params.get('elect_id', 1)
        level = user.level
        queryset = NewYearsShoppingFestivalElectProduct.objects.filter(is_match=1, elect_id=elect_id).order_by('-like_count', 'id')[:10]
        rank = 1
        product_lists = []
        check_level = 1
        response_data = {}
        for query in queryset:
            if query.level_id == level.id:
                check_level = 0
            data = NewYearsShoppingFestivalElectProductListModelSerializer(query).data
            data['rank'] = rank
            product_lists.append(data)
            rank += 1
        response_data['product_lists'] = product_lists
        response_data['product'] = {}
        return Response(response_data, status=status.HTTP_200_OK)


class NewYearsShoppingFestivalElectProductLikeModelViewSet(ModelViewSet):

    pagination_class = ElectLikePage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('product__product_title',)
    serializer_class = NewYearsShoppingFestivalElectProductLikeListModelSerializer
    filter_class = NewYearsShoppingFestivalElectProductLikeFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = NewYearsShoppingFestivalElectProductLike.objects.filter(customeruservice_id=user.id).order_by('-create_time')
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.request.query_params.get('page', '1')
        if page != '1':
            try:
                if '_mutable' in self.request.query_params.__dict__:
                    self.request.query_params.__dict__['_mutable'] = True
                self.request.query_params['date'] = queryset[(int(page)-1)*10-1].create_time.strftime("%Y-%m-%d")
            except:
                pass
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class AfterSaleReasonModelViewSet(ModelViewSet):

    queryset = AfterSaleReason.objects.filter(is_delete=0)
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    serializer_class = AfterSaleReasonModelSerializer
    filter_class = AfterSaleReasonFilter


class AfterSaleApplicationFormModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = AfterSaleApplicationFormFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = AfterSaleApplicationForm.objects.filter(customeruservice_id=user.id)
        return queryset.order_by('-id')

    def retrieve(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.form_status == 5:
            if instance.expired_time <= datetime.datetime.now():
                order = instance.order
                order.state = instance.order_status
                order.save()
                instance.form_status = 4
                instance.save()
                OrderAdvance.objects.create(
                    order_id=order.id,
                    status=3,
                    remark='消费者超时未寄货',
                    customeruservice_id=user.id
                )
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def get_serializer_class(self):
        if self.action == 'list':
            return AfterSaleApplicationFormListModelSerializer
        else:
            return AfterSaleApplicationFormRetrieveModelSerializer

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.form_status != 5:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        express_array = self.request.data.get('express_array', None)
        if not all([express_array]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        order = instance.order
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                for express in express_array:
                    try:
                        ExpressType.objects.get(id=express['express_type_id'])
                    except:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '无效快递类型'}, status=status.HTTP_400_BAD_REQUEST)
                    express_data = {}
                    express_data['express_type_id'] = express['express_type_id']
                    express_data['express_number'] = express['express_number']
                    express_data['nature'] = 2
                    express, create = Express.objects.get_or_create(defaults=express_data, express_number=express['express_number'])
                    relevance_data = {}
                    relevance_data['order_id'] = order.id
                    relevance_data['express_id'] = express.id
                    ExpressOrderRelevance.objects.get_or_create(defaults=relevance_data, order_id=relevance_data['order_id'], express_id=relevance_data['express_id'])
                instance.form_status = 9
                instance.save()
                OrderAdvance.objects.create(
                    order_id=order.id,
                    status=3,
                    remark='添加快递单号',
                    customeruservice_id=user.id
                )
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '操作失败'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.form_status != 8:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        order = instance.order
        order.state = instance.order_status
        order.save()
        instance.form_status = 4
        instance.save()
        OrderAdvance.objects.create(
            order_id=order.id,
            status=3,
            remark='消费者取消售后',
            customeruservice_id=user.id
        )
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def partial_update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.form_status != 10:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        order = instance.order
        instance.form_status = 6
        instance.save()
        order.state = instance.order_status
        order.save()
        OrderAdvance.objects.create(
            order_id=order.id,
            status=3,
            remark='消费者确认换货',
            customeruservice_id=user.id
        )
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def deliver_goods(self, request):
        user = self.request.iser
        express_array = self.request.data.get('express_array', None)
        form_id = self.request.data.get('form_id', None)
        if not all([express_array, form_id]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=form_id)
        except:
            return Response({'error': '无效申请单id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.form_status != 5:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        order = instance.order
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                for express in express_array:
                    try:
                        ExpressType.objects.get(id=express['express_type_id'])
                    except:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '无效快递类型'}, status=status.HTTP_400_BAD_REQUEST)
                    express_data = {}
                    express_data['express_type_id'] = express['express_type_id']
                    express_data['express_number'] = express['express_number']
                    express_data['nature'] = 2
                    express, create = Express.objects.get_or_create(defaults=express_data, express_number=express['express_number'])
                    relevance_data = {}
                    relevance_data['order_id'] = order.id
                    relevance_data['express_id'] = express.id
                    ExpressOrderRelevance.objects.get_or_create(defaults=relevance_data, order_id=relevance_data['order_id'], express_id=relevance_data['express_id'])
                instance.form_status = 9
                instance.save()
                OrderAdvance.objects.create(
                    order_id=order.id,
                    status=3,
                    remark='消费者退货',
                    customeruservice_id=user.id
                )
                # try:
                #     express_send.delay({'id': instance.id, 'express_id': express.id})
                # except:
                #     pass
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '操作失败'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def receive_goods_again(self, request):
        user = self.request.iser
        form_id = self.request.data.get('form_id', None)
        if not form_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=form_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.form_status != 10:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        instance.form_status = 6
        instance.save()
        order = instance.order
        order.state = 14
        order.save()
        OrderAdvance.objects.create(
            order_id=instance.order_id,
            status=4,
            remark='消费者确认收货',
            customeruservice_id=user.id
        )
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class ExpressModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = ExpressFilter
    search_fields = ('express_number',)

    def get_queryset(self):
        user = self.request.iser
        queryset = Express.objects.filter(expressorderrelevance__order__customeruservice_id=user.id).distinct().order_by('-id')
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        customer_send = len(queryset.filter(nature=2))
        merchant_send = len(queryset.filter(nature=1))
        nature = self.request.query_params.get('nature', None)
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['merchant_send'] = str(merchant_send)
        self.request.data['customer_send'] = str(customer_send)
        if nature:
            queryset = queryset.filter(nature=nature)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def get_serializer_class(self):
        if self.action == 'list':
            return ExpressListModelSerializer
        else:
            return ExpressRetrieveModelSerializer


class ExpressTypeModelViewSet(ModelViewSet):

    queryset = ExpressType.objects.all()
    serializer_class = ExpressTypeModelSerializer
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('express_type_name', )

    def choices_expresstype(self, request):
        express_number = self.request.query_params.get('express_number', '')
        url = f'https://alayn.baidu.com/express/appdetail/get_com?num={express_number}'
        response = requests.get(url=url)
        try:
            result = response.json()
            express_type = ExpressType.objects.filter(express_type=result['data']['company']).first()
            if express_type:
                return Response(ExpressTypeModelSerializer(express_type).data, status=status.HTTP_200_OK)
            else:
                return Response({}, status=status.HTTP_200_OK)
        except:
            return Response({}, status=status.HTTP_200_OK)





